An array is a data structure that with 'slots' that are accessed using an integer index, typically starting on 0 or 1. Python's list is essentially an array - Java has two similar data structures. The first is the native array type, which has a fixed number of slots. The second is the ArrayList, which is the closest to Python's list, since it supports changing the length. Notice that for both, you need to declare what type of variables it's going to be holding.

Declaration

Java native arrays and Python lists can both created using curly braces {...}.

Arrays in Java
 int[] a = new int[]{3, 5, 7}; // or just {3, 4, 7}
 a[0] = 1; // a is {1, 5, 8}
 a = new int[5]; // a is {0, 0, 0, 0, 0}
Arrays in Python
 A = ["spam", "baked beans", "sausage", "spam"]
 B = A[0:2] # B is ["spam", "baked beans"]
 B[1] = "spam" # B is ["spam", "spam"]
 B = B + ["Eric"] # B is ["spam", "spam", "Eric"]

In Java, strings are not arrays, as in Python. You need to use the String class and methods to access individual characters, while in Python, strings can be treated as immutable arrays of characters.

Strings in Java
 String s = "spam";
 char c = s.charAt(1); // c is 'p'
Strings in Python
 S = "spam"
 c = S[1] # c = "p"
  • No labels