Enhanced ‘for’ loop causes an ArrayIndexOutOfBoundsException

In this case, i will be assigned to each element in the array – it is not an index into the array.

What you want to do is:

for(int i : arrs)
{
    System.out.println(i);
}

In your code, you’re trying to select the integer at the array index referenced by the iteration object. In other words, your code is equivalent to:

for(int idx = 0; idx < arrs.length; idx++)
{
    int i = arrs[idx];
    System.out.println(arrs[i]);
}

Leave a Comment