Java › Arrays & Multidimensional Arrays

How does Java handle array bounds checking, and what exception is thrown when accessing an invalid index?

Intermediate

Answer

Every array access in Java is automatically bounds-checked by the JVM at runtime, throwing ArrayIndexOutOfBoundsException (an unchecked RuntimeException) if the index is negative or greater than or equal to the array's length -- this automatic checking prevents the memory-corruption vulnerabilities common in languages like C that allow unchecked buffer access, at the cost of a small but generally negligible runtime overhead for each array access, though modern JIT compilers can often eliminate redundant bounds checks through optimization when they can statically prove an index is always safe.
int[] arr = {1, 2, 3};
try {
    System.out.println(arr[5]);  // throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index: " + e.getMessage());
}
Real-world example A parsing routine iterating a fixed-size array with an off-by-one loop bound (using <= instead of <) is caught immediately in testing by the resulting ArrayIndexOutOfBoundsException, illustrating how Java's automatic bounds checking surfaces this class of bug loudly and immediately rather than causing silent memory corruption as it might in an unmanaged language.

Common follow-ups: How does JIT compiler bounds-check elimination work, and under what conditions can it safely skip the runtime check?;What's the performance cost of bounds checking in a very tight, performance-critical loop?