Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Array element access: array[index]

The expression array[index] selects an array element for reading or writing. Indices start at zero, and Java checks their bounds at run time.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

array[index]

array[index] denotes a variable that is an array component. You can read its value or assign a new one. A final array reference does not prevent changes to its elements.

Valid indices satisfy 0 <= index && index < array.length. An empty array has no valid index. After unary numeric promotion, the index type must be int; byte, short, and char are allowed, but long is not.

Java evaluates the array reference first, then the index. When reading an element, if both evaluations complete normally, Java checks for a null reference first (throwing NullPointerException), then checks the index bounds (throwing ArrayIndexOutOfBoundsException for an out-of-range index). Avoid side effects in the index: it is evaluated even for a null reference.

In the simple assignment array[index] = rhs, if the array reference and index evaluations complete normally, Java evaluates rhs before either check. If evaluating rhs throws an exception, that exception takes precedence over either the null-reference or the bounds exception.

Examples

public class Main {
    public static void main(String[] args) {
        final int[] array = {10, 20, 30};
        int index = 1;
        System.out.println(array[index]);
        array[index] = 25;
        System.out.println(array[index]);
        System.out.println(array[array.length - 1]);
    }
}

Result

20
25
30

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources