Search code examples
javafinal

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


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?


Solution

  • 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);
        }
    }