Arrays are a special type of object. Arrays are an efficient container for primitive values or object references. ArrayList or HashSet object are also containers for object references, and these have many convenience methods useful to object programmers. List and sets can be added to, but arrays have a fixed length when they are created, and this cannot be changed. Resizing an array involves creating a new array and copying values from old to new. However, arrays are often a better choice of container because they can hold primitive data values and have lower overheads and higher performance characteristics in many situations.

Arrays can be single or multiple dimensional. Like other objects, arrays are instantiated using the ‘new’ operator. The new operator requires the data type, followed by pairs of square brackets the define the number of dimensions, and optionally the number of elements to allocate within each dimension. For example,

values = new int[2][3];

will allocate a new two-dimensional array of primitive int values. Primitive arrays are initialized with zero values (false for Boolean arrays). Object arrays are initialized with null values.

Array constructors can optionally provide an initializer:

values = new int[][] {{1,2,3}, {4,5,6}};

Initializers are enclosed in braces. When initializing a multi-dimensional array the sub-arrays elements are also enclosed in braces.

Array values are referenced by the array variable name and using bracket suffixes. Java arrays are indexed starting at zero: the first element in the array is position 0, the second element in the array is position 1, etc. The following example retrieve the second inner element or the second outer element:

values = new int[][] {{1,2,3}, {4,5,6}};
print(values[1][1]+" is 5");

The length of an array is contained in the object length field:

values = new int[][] {{1,2,3}, {4,5,6}};
print("The outer array dimension is "+values.length);
print("The dimension of the second inner array element is "+values[1].length);

Search the web for “Java arrays” for more details.