Card 04/ 08

GotchaDifficulty: Intermediate1 min

ArrayIndexOutOfBoundsException: Reading the Message

A report that has worked for months throws on one customer, at an index nothing in your code contains.

Java checks every array access while the program runs, and an index below 0 or at or above the length throws ArrayIndexOutOfBoundsException. The message names both the index asked for and the length that exists, which is usually enough to see the mistake.

A report that has worked for months throws on one customer. The index in the message is a number nothing in your code contains:

text
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 12
	at Report.monthName(Report.java:31)
java
String[] names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

String monthName(int month) {
    return names[month];
}

Twelve names, indexes 0 to 11. The caller passed 12 because it had a month number rather than an offset, and December is the twelfth month and the eleventh index. The array did exactly what it was told.

The message is worth reading closely, because it carries both halves of the answer. Index 12 is what was asked for; for length 12 is what exists. If those two numbers are equal, something counted from one and indexed from zero. If the index is negative, a subtraction went below the start.

Convert at the boundary, not inside: take the month number from the caller and subtract one where it enters, so the rest of the method works in offsets and nothing else has to remember which convention it is in.