Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 938
Muhammad Gelbana Avatar asked Feb 17 '14 22:02

Muhammad Gelbana


2 Answers

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.

like image 178
Oliver Charlesworth Avatar answered Sep 22 '22 03:09

Oliver Charlesworth


It simply means you cannot modify the object reference after it has been set. So in this case, "final" applies only within each iteration. :D

like image 29
BruceWayne Avatar answered Sep 23 '22 03:09

BruceWayne