In the example, a new array of a different size could be assigned to the array variable ia at any time.
You access array elements by their position in the array. The first element of an array has index 0 (zero), and
the last element has index length1. You access an element by using the name of the array and the index
enclosed between [ and ]. In our example, the first element of the array is ia[0] and last element of the
array is ia[2]. Every index use is checked to ensure that it is within the proper range for that array, throwing
an ArrayIndexOutOfBoundsException if the index is out of bounds.[8] The index expression must be
of type intthis limits the maximum size of an array.
[8] The range check can often be optimized away when, for example, it can be proved that a
loop index variable is always within range, but you are guaranteed that an index will never be
used if it is out of range.
The length of an array is available from its length field (which is implicitly public and final). In our
example, the following code would loop over the array, printing each value:
for (int i = 0; i < ia.length; i++)
System.out.println(i + ": " + ia[i]);
An array with length zero is said to be an empty array. There is a big difference between a null array
reference and a reference to an empty arrayan empty array is a real object, it simply has no elements. Empty
arrays are useful for returning from methods instead of returning null. If a method can return null, then
users of the method must explicitly check the return value for null before using it. On the other hand, if the
method returns an array that may be empty, no special checking is needed provided the user always uses the
array length to check valid indices.
If you prefer, you can put the array brackets after the variable name instead of after the type:
int ia[] = new int[3];
This code is equivalent to the original definition of ia. However, the first style is preferable because it places
the type declaration entirely in one place.
7.4.1. Array Modifiers
The normal modifiers can be applied to array variables, depending on whether the array is a field or local
variable. The important thing to remember is that the modifiers apply to the array variable not to the elements
of the array the variable references. An array variable that is declared final means that the array reference
cannot be changed after initialization. It does not mean that array elements cannot be changed. There is no
way to apply any modifiers (specifically final and volatile) to the elements of an array.
7.4.2. Arrays of Arrays
You can have arrays of arrays. The code to declare and print a two-dimensional matrix, for example, might
look like this:
float[][] mat = new float[4][4];
setupMatrix(mat);
for (int y = 0; y < mat.length; y++) {
for (int x = 0; x < mat[y].length; x++)