Search code examples
javaforeachfinal

How does having a final variable in a foreach loop work


Consider this piece of code

public static void main(String[] args) {
    for(final String s : Arrays.asList("a","b","c")){
        System.out.println(s);
    }
}

This code doesn't serve a specific purpose but to demonstrate the usage of final foreach-loop variables.

How does this work ? How can a single variable be final yet it is assigned a different value with each loop. Or is this variable declared multiple times in different scopes\stacks ?


Solution

  • This is explained in the Java Language Specification (JLS), 14.14.2:

    The enhanced for statement has the form:

    EnhancedForStatement:
        for ( FormalParameter : Expression ) Statement
    
    FormalParameter:
        VariableModifiers_opt Type VariableDeclaratorId
    
    VariableDeclaratorId:
        Identifier
        VariableDeclaratorId []
    

    ...

    The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
        VariableModifiers_opt TargetType Identifier =
            (TargetType) #i.next();
        Statement
    }
    

    Thus, the Identifier is redeclared on each iteration of the loop.