ArrayIndexOutOfBoundsException

suggest change

The ArrayIndexOutOfBoundsException is thrown when a non-existing index of an array is being accessed.

Arrays are zero-based, so the index of the first element is 0 and the index of the last element is array.length - 1.

Therefore, any request for an array element by the index i has to satisfy the condition 0 <= i < array.length, otherwise the ArrayIndexOutOfBoundsException will be thrown.


The following code is a simple example where an ArrayIndexOutOfBoundsException is thrown.

String[] people = new String[] { "Carol", "Andy" };

// An array will be created:
// people[0]: "Carol"
// people[1]: "Andy"

// Notice: no item exists at index 2. Trying to access it triggers the exception:
try {
    System.out.println(people[2]);
} catch (ArrayIndexOutOfBoundsException exception) {
    System.out.println(exception);
}
java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

The exception’s detail message includes the illegal index (2 in this example), which helps find the cause. On Java 8 the message is typically just that index; from Java 9 it also includes the array length.


To avoid this, simply check that the index is within the limits of the array:

int index = 2;
if (index >= 0 && index < people.length) {
    System.out.println(people[index]);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents