Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

ArrayIndexOutOfBoundsException

Thrown when an array is accessed at an index that does not exist.

Available since: Java 1.0

Syntax

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException

Examples

The classic <= mistake in a loop:

void main() {
    int[] nums = {1, 2, 3};
    try {
        for (int i = 0; i <= nums.length; i++) {
            IO.println(nums[i]);
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        IO.println(e.getMessage());
    }
}

Output:

1
2
3
Index 3 out of bounds for length 3

Notes

Array indexes go from 0 to length - 1. Most often the error comes from the condition i <= length instead of i < length, or from a negative index. A for-each loop over the array avoids it. For lists the parent class IndexOutOfBoundsException is thrown.

See also

In the tutorial

  • What exceptions are — Exceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.

Thanks for reading!

Donate to the site — we work hard for you.