ArrayIndexOutOfBoundsException

Naveen AnamaneniUpdated · 4 min read

A coach has berths 1 to 72. Ask for berth 73, and the conductor tells you there's no such berth. Java does the same when you ask an array for a position that doesn't exist: it stops the program with an ArrayIndexOutOfBoundsException. It's the most common array error, and it's almost always caused by one of three small mistakes.

The Message Tells You Everything

Berths.java
public class Berths {
    public static void main(String[] args) {
        int[] berths = {11, 12, 13};
        System.out.println(berths[3]);
    }
}
Terminal output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    at Berths.main(Berths.java:4)

Read it in three parts:

  1. ArrayIndexOutOfBoundsException: you used an index that doesn't exist.
  2. Index 3 out of bounds for length 3: you asked for index 3, but the array has length 3, so valid indexes are 0, 1 and 2.
  3. at Berths.main(Berths.java:4): the file and line where it happened.

Try it yourself: change the index to -1. What does the message say now?

Cause 1: Off by One in a Loop

OffByOne.java
for (int i = 0; i <= marks.length; i++) {   // <= reaches marks.length
    total += marks[i];
}

i <= marks.length lets i reach length, one past the last index. Use i < marks.length. If you start counting at 1, remember that the element is marks[i - 1].

Cause 2: An Empty Array

FirstArg.java▶ Try it
public class FirstArg {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Please give a city name");
            return;
        }
        System.out.println("City: " + args[0]);
    }
}
Output
Please give a city name

With no command-line arguments, args has length 0, so even args[0] is out of bounds. Check the length first, as this program does.

Cause 3: Using the Wrong Array's Length

When two arrays should match, such as names and scores, looping over names.length but reading scores[i] fails as soon as scores is shorter. Use the length of the array you're actually reading, or check that both lengths are equal first.

It's a Runtime Error

The compiler can't catch this mistake, because the index is often only known while the program runs. That's why Java checks every array access at runtime: it's part of what makes Java memory-safe (see "Features of Java"). A later lesson on exceptions shows how errors like this can be caught, but the right fix is almost always to correct the index, not to catch the exception.

Common Mistakes

Using <= with length. Use <.

Assuming input is never empty. Check length before reading [0].

Catching the exception to hide the bug. It hides a real mistake in your logic. Fix the index instead.

Practice

  1. Easy: Fix the OffByOne loop and make it print the total of {10, 20, 30}.
  2. Harder: Write a method static int safeGet(int[] a, int i) that returns a[i], or -1 when i is out of range, without causing the exception.

Quick check: Out of bounds

4 questions
1Which indexes are valid for an array of length 5?
2What does Index 3 out of bounds for length 3 mean?
3Which loop header causes this exception?
4Is this exception caught by the compiler?

Key Takeaways

Was this tutorial helpful?

Lesson 78 of 482