🧱 Arrays · Beginner

ArrayIndexOutOfBoundsException in Java

Accessing index < 0 or >= length.

🧩 The mysteryPython lets you write a[-1] to get the last element. Try it in Java and your program crashes. Which language is right?

Guarded slots

Every array access is checked at runtime. An index below 0, or **equal to or above length, throws ArrayIndexOutOfBoundsException**. Java never lets you touch memory outside an array.

int[] a = new int[3]; // valid: 0, 1, 2
a[2] = 1;  // fine
a[3] = 1;  // throws
a[-1] = 1; // throws too
🔮 Predict it

Your turn

What happens?

int[] a = {7, 8, 9};
System.out.println(a[-1]);
  1. Prints 9
  2. Prints 7
  3. Throws ArrayIndexOutOfBoundsException
Show the answer

Java has no negative indexing: a[-1] doesn't wrap around to the end, it throws. For the last element, write a[a.length - 1].

Compiles fine, fails later

The compiler doesn't check index values. a[5] = 1 on a 3-element array compiles perfectly and throws only when that line runs. Modern JDKs give a helpful message: Index 5 out of bounds for length 3.

int[] a = new int[3];
a[5] = 1; // compiles!
// runtime: Index 5 out of bounds
//          for length 3
⚠️ The trap

The <= trap

The classic cause is an off-by-one loop: i <= a.length also tries i == a.length, one past the end. The loop processes every valid element and then crashes. **Always loop with i < a.length.**

int[] a = {1, 2, 3};
for (int i = 0; i <= a.length; i++) {
    System.out.println(a[i]); // i=3 throws
}

Walking backwards

✗ Crashes at once
for (int i = a.length; i >= 0; i--) {
    System.out.println(a[i]);
}

The first index used is a.length, which is past the end.

✓ Correct
for (int i = a.length - 1; i >= 0; i--) {
    System.out.println(a[i]);
}

Start at the last valid index, length - 1, and include 0.

🔮 Predict it

Another way backwards

No crash this time. What prints?

int[] a = {1, 2, 3};
for (int i = a.length; i > 0; i--) {
    System.out.print(a[i - 1]);
}
  1. 321
  2. 32
  3. 21
  4. 123
Show the answer

i runs 3, 2, 1, but the code reads a[i - 1]: indexes 2, 1, 0. All valid! Shifting the index inside the loop is another safe pattern.

🤔 Think first

The emptiest array

Is new int[0] legal? If so, what's its first valid index?

Think about it, then reveal the answer

It's perfectly legal, with length 0. But it has no valid index at all: even empty[0] throws ArrayIndexOutOfBoundsException. Methods often return empty arrays instead of null to mean "no results".

💼 In the real world

In real projects

Heartbleed (2014) was a missing bounds check in OpenSSL's C code: attackers could read chunks of server memory, including passwords and keys. In Java, that same mistake throws an exception instead of leaking data. Bounds checks are a big reason Java is called memory-safe.

Key takeaways

  1. Valid indexes: 0 to length - 1
  2. a[-1] doesn't wrap around; it throws
  3. It compiles fine and fails only at runtime
  4. Loop with i < a.length, not i <= a.length
🤯 Did you know?

The JIT compiler can often prove an index is always in range, for example in for (i = 0; i < a.length; i++), and silently remove the bounds check. Safety at almost no cost.

Practice questions

What does this print?

int[] a = {1, 2, 3};
int sum = 0;
for (int i = 0; i <= a.length; i++) {
    sum += a[i];
}
System.out.println(sum);
  1. 6
  2. 3
  3. Compile error
  4. Throws ArrayIndexOutOfBoundsException
Check your answer

Throws ArrayIndexOutOfBoundsException. With <=, the loop also tries i = 3, but the valid indexes are 0, 1 and 2. The exception happens before sum is printed.

What happens with int[] a = new int[3]; a[5] = 1; ?

  1. Compile error: index out of range
  2. It compiles, then throws ArrayIndexOutOfBoundsException when run
  3. The array silently grows to length 6
  4. The write is silently ignored
Check your answer

It compiles, then throws ArrayIndexOutOfBoundsException when run. The compiler doesn't check index values. The bounds check happens at runtime, when the assignment executes.

Next: you create an array and never fill it. What's inside? Zeros? Garbage? Something stranger?