Course contentsShow
← Java
Lesson 795 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

ArrayIndexOutOfBoundsException and Bounds Checking

Learn why array access throws exceptions and how to safely work with array indices.

ArrayIndexOutOfBoundsException and Bounds Checking

What you'll learn: How Java prevents dangerous memory access when you try to read or write beyond an array's boundaries.

Why Arrays Throw Exceptions

Arrays in Java have a fixed size set at creation. Every array knows its length and enforces strict rules: you can only access indices from 0 to length - 1. If you try to access index -1, or index 5 in a 3-element array, Java doesn't silently read garbage memory or crash unpredictably—it throws an ArrayIndexOutOfBoundsException.

This is a safety feature. Unlike some languages that let you accidentally read or overwrite random memory, Java checks every array access at runtime. This is called bounds checking.

When This Exception Occurs

int[] numbers = new int[3]; // Valid indices: 0, 1, 2

System.out.println(numbers[0]);  // OK
System.out.println(numbers[3]);  // Throws ArrayIndexOutOfBoundsException
System.out.println(numbers[-1]); // Also throws

Since ArrayIndexOutOfBoundsException extends RuntimeException, it's unchecked—you don't have to declare or catch it, though you should prevent it.

Working Safely with Array Indices

Always validate before accessing:

int index = getUserInput();

if (index >= 0 && index < numbers.length) {
    System.out.println(numbers[index]); // Safe
} else {
    System.out.println("Invalid index");
}

Use length-based loops:

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]); // Never out of bounds
}

Think of an array like a row of numbered mailboxes: if there are only boxes 0–2, asking for box 5 makes no sense. Java stops you immediately rather than letting you peek into someone else's mail.

Key Takeaway: ArrayIndexOutOfBoundsException prevents unsafe memory access by enforcing that every array index falls within 0 to length - 1; always validate indices before use.