CKTIS / Java
ArrayIndexOutOfBoundsException — array index out of range
ArrayIndexOutOfBoundsException signals array access with a negative index or an index greater than or equal to the array length. A valid index satisfies 0 <= index && index < array.length.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
array[index]
new ArrayIndexOutOfBoundsException()
new ArrayIndexOutOfBoundsException(index)
new ArrayIndexOutOfBoundsException(s)ArrayIndexOutOfBoundsException indicates an attempt to access an array element outside its bounds. For a nonempty array, indices run from 0 to array.length - 1; an empty array has no valid index. Java checks bounds at runtime. Reading through a null reference instead throws NullPointerException.
The class extends IndexOutOfBoundsException and indirectly RuntimeException, making it unchecked: you do not have to catch it or declare it in throws. IndexOutOfBoundsException is a more general indexing error type, not limited to arrays.
The constructors are ArrayIndexOutOfBoundsException(), ArrayIndexOutOfBoundsException(int index), and ArrayIndexOutOfBoundsException(String s): respectively without a message, with the invalid index, and with a supplied message. The message format for the int variant is unspecified; do not base tests on it.
To prevent the error, check 0 <= index && index < array.length; in a loop, use index < array.length, not index <= array.length. The example deliberately catches the exception to demonstrate an off-by-one error: values.length is already outside the array. In ordinary code, fix the index calculation rather than hiding the bug by catching the exception.
Examples
public class Main {
public static void main(String[] args) {
int[] values = {10, 20, 30};
System.out.println(values[values.length - 1]);
try {
System.out.println(values[values.length]);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}Result
30 ArrayIndexOutOfBoundsException
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.