Java: ArrayIndexOutOfBoundsException in for loop

Array indexes are zero-based.

The last valid index for an array of N elements is N − 1.

You have most likely written…

for (int i = 0; i <= arr.length; i++) {
    something(arr[i]);
}

…where it sohuld be

for (int i = 0; i < arr.length; i++) {
    something(arr[i]);
}

ArrayIndexOutOfBoundsException

An ArrayIndexOutOfBoundsException is thrown when the program tries to access an element at an invalid index.

The array indexes are zero-based, so for an array with N elements (array.length == N) the valid indexes are 0…N − 1.

Example: For an array created like this:

int[] arr = { 17, 55, 2, 10 };

the memory looks like this:

−3 −2 −1 17 0 55 1 2 2 10 3 4 5 6 Index: Valid indexes

That is, with 4 elements, the greatest valid index is 3.

Comments

Be the first to comment!