Course contentsShow
← Java
Lesson 245 of 2,8706. ArraysFree lesson

ArrayIndexOutOfBoundsException and Bounds Checking

Understand what happens when accessing invalid indices and how Java enforces array bounds at runtime.

What You'll Learn

You'll discover what happens when you try to access an array position that doesn't exist, and how Java protects you from dangerous memory errors at runtime.

Arrays Have Strict Boundaries

Every array in Java has a fixed length, and you can only access valid indices from 0 to length - 1. Java doesn't trust you to always get this right—it actively checks every array access while your program runs. This is called bounds checking.

If you attempt to access an invalid index (negative, or greater than or equal to the array's length), Java immediately stops your program and throws an ArrayIndexOutOfBoundsException.

Why This Matters

Think of an array like a row of numbered mailboxes. If you ask for mailbox -1 or mailbox 100 when only boxes 0 through 9 exist, the postal clerk won't let you proceed. Java acts as that clerk, preventing you from reading or writing to memory that doesn't belong to your array.

What the Exception Looks Like

int[] numbers = {10, 20, 30};
int value = numbers[5];  // Crashes! Valid indices: 0, 1, 2

This produces:

ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3

The exception message tells you exactly which invalid index you tried and what the array's actual length is.

Common Mistakes

  • Off-by-one errors: Using i <= numbers.length instead of i < numbers.length in loops
  • Empty arrays: Forgetting that a zero-length array has no valid indices at all
  • Negative indices: Unlike some languages, Java doesn't support counting backwards from the end

Key Takeaway: Java enforces array boundaries at runtime by throwing ArrayIndexOutOfBoundsException for any invalid index access, protecting your program from unpredictable memory corruption.