tags:

views:

165

answers:

2

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?

+18  A: 

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);
    }
}
Travis Gockel
Good one............. +1 for expanding my brain.
Tony Ennis
+2  A: 

See @TravisG for an explanation of the scoping rules involved. The only reason why you would use a final loop variable like this is if you needed to close over it in an anonymous inner class.

import java.util.Arrays;
import java.util.List;

public class FinalLoop {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(new Integer[] { 0,1,2,3,4 });
        Runnable[] runs = new Runnable[list.size()];

        for (final int i : list) {
            runs[i] = new Runnable() {
                    public void run() {
                        System.out.printf("Printing number %d\n", i);
                    }
                };
        }

        for (Runnable run : runs) {
            run.run();
        }
    }
}

The loop variable is not in the scope of the Runnable when it is executed, only when it is instantiated. Without the final keyword the loop variable wouldn't be visible to the Runnable when it is eventually run. Even if it was, it would be the same value for all the Runnables.

Btw, about 10 years ago you might have seen a very small speed improvement in using final on a local variable (in some rare occasions); that hasn't been the case for a long. Now the only reason to use final is to permit you to use a lexical closure like this.

Recurse
Or to document the intent of not making this variable reassignable.
seanizer
No! If you do this you now have to semantic meanings for the same syntax - one has real uses; the other is redundant unless you method is far far far too long. Only use final to indicate you intend to close over the parameter, _never_ to indicate single assignment.
Recurse