arrays – What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

arrays – What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

Your first port of call should be the documentation which explains it reasonably clearly:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

So for example:

int[] array = new int[5];
int boom = array[10]; // Throws the exception

As for how to avoid it… um, dont do that. Be careful with your array indexes.

One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.

int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
    System.out.println(array[index]);
}

That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for statement here would be:

for (int index = 0; index < array.length; index++)

(Thats assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)

if (index < 0 || index >= array.length) {
    // Dont use this index. This is out of bounds (borders, limits, whatever).
} else {
    // Yes, you can safely use this index. The index is present in the array.
    Object element = array[index];
}

See also:


Update: as per your code snippet,

for (int i = 0; i<=name.length; i++) {

The index is inclusive the arrays length. This is out of bounds. You need to replace <= by <.

for (int i = 0; i < name.length; i++) {

arrays – What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

From this excellent article: ArrayIndexOutOfBoundsException in for loop

To put it briefly:

In the last iteration of

for (int i = 0; i <= name.length; i++) {

i will equal name.length which is an illegal index, since array indices are zero-based.

Your code should read

for (int i = 0; i < name.length; i++) 
                  ^

Leave a Reply

Your email address will not be published.