JVM Knowledge

A component of an array is accessed by an array access expression (§15.10.3) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].

All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

Example 10.4-1. Array Access

class Gauss {
    public static void main(String[] args) {
        int[] ia = new int[101];
        for (int i = 0; i < ia.length; i++) ia[i] = i;
        int sum = 0;
        for (int e : ia) sum += e;
        System.out.println(sum);
    }
}

This program produces the output:

5050

The program declares a variable ia that has type array of int, that is, int[]. The variable ia is initialized to reference a newly created array object, created by an array creation expression (§15.10.1). The array creation expression specifies that the array should have 101 components. The length of the array is available using the field length, as shown. The program fills the array with the integers from 0 to 100, sums these integers, and prints the result.

Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values.

An attempt to access an array component with a long index value results in a compile-time error.

All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown (§15.10.4).