Why do I get an ArrayIndexOutOfBoundsException?

edited November 2014 in Common Questions

Why do I get an ArrayIndexOutOfBoundsException?

A bit less common that its cousin NullPointerException, it still puzzles newcomers to the language.

Array? Index? Bounds? Exception?

I won't explain in detail what is an array here. If you have this error, you already tried to use them, so you are supposed to know at least the bases... :-)

Index is the number indicating which slot in the array was attempted to be used (read or write).

Bounds are the limits of the array. The maximum and minimum indexes. The minimum is always 0 (zero). The maximum is the size of the array minus one.

Exceptions are explained in more detail in the above mentioned article on NullPointerException. I won't duplicate it here.

Why do I get this error?

Well, as you can guess from the above, you get this error when you try to access an array with an index out of its bounds. You can get it with any negative index value, of course. Or with an index above the maximum index, which is the most common cause.

Often, people forget that the indexes start at 0. In some programming languages (like Lua, Pascal, ...) they can start at 1. Since they start at 0, that means that the maximum index is <array length> - 1, ie. if you declare an array of length 10, for example, the possible indexes go from 0 to 9.

That's why most loops operating on an array use < in the end condition of the loop:

int[] values = new int[10];
for (int i = 0; i < values.length; i++)
{
  values[i] = i * 2;
}

Notes:

  • It is better to use values.length instead of 10 in the condition: thus if you change the size, the loop will adapt itself automatically.
  • Notice the <, not <= operator in the conditional part.

If you have this exception and wonder what is wrong (sometime, it is less obvious than the above), a good idea is to println the values of the indexes. Thus you can see when it is going out of bounds.

Tagged:
Sign In or Register to comment.