How does "final int i" work inside of a Java for loop?

Abe picture Abe · Oct 12, 2010 · Viewed 15.2k times · Source

I was surprised to see that the following Java code snippet compiled and ran:

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

where listOfNumbers is an array of integers.

I thought final declarations got assigned only once. Is the compiler creating an Integer object and changing what it references?

Answer

Travis Gockel picture Travis Gockel · Oct 12, 2010

Imagine that shorthand looks a lot like this:

for (Iterator<Integer> iter = listOfNumbers.iterator(); iter.hasNext(); )
{
    final int i = iter.next();
    {
        System.out.println(i);
    }
}