ArrayIndexOutOfBoundsException
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
public class Berths {
public static void main(String[] args) {
int[] berths = {11, 12, 13};
System.out.println(berths[3]);
}
}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:
ArrayIndexOutOfBoundsException: you used an index that doesn't exist.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.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
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
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]);
}
}Please give a city nameWith 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
- Easy: Fix the
OffByOneloop and make it print the total of{10, 20, 30}. - Harder: Write a method
static int safeGet(int[] a, int i)that returnsa[i], or -1 wheniis out of range, without causing the exception.
Key Takeaways
Was this tutorial helpful?