Error reference
Java error: ArrayIndexOutOfBoundsException
This page is part of Intro to Java with Greenfoot. It assumes you have reached lesson 5.1. Opening it is not counted against you and is not tracked as progress.
The message
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
What it actually means
You asked an array for a slot it does not have. The array is fine; the index is wrong.
The usual causes
Ranked by how often each one turns out to be the answer. Work down the list.
- A loop using <= instead of <, so it runs one past the end. The message shows an index exactly equal to the length.
- Using a.length as an index instead of a.length - 1.
- On a 2D array, the two subscripts are swapped and the grid is not square.
- A level or wave counter that has grown past the last entry in its array.
How to fix it
Read the message: it names the index you tried AND the length. If the index equals the length exactly, change <= to < in the loop, or use a.length - 1 for the last element. On a 2D array, check that row is the FIRST subscript.