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:
That is, with 4 elements, the greatest valid index is 3.
Comments
Be the first to comment!