The ArrayIndexOutOfBoundsException
is thrown when a non-existing index of an array is being accessed.
Arrays are zero-based indexed, so the index of the first element is 0
and the index of the last element is the array capacity minus 1
(i.e. 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 on index 2. Trying to access it triggers the exception:
System.out.println(people[2]); // throws an ArrayIndexOutOfBoundsException.
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at your.package.path.method(YourClass.java:15)
Note that the illegal index that is being accessed is also included in the exception (2
in the example); this information could be useful to find the cause of the exception.
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]);
}