Enhanced for loop compiling fine for JDK 8 but not 7

This should actually compile fine for JDK 7 and 8.

Quoting JLS section 14.14.2 (which is the same for the Java 7 specification):

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

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

Rewriting the enhanched for loop with Iterator

for (String text : text) {...}


for (Iterator<String> it = text.iterator(); it.hasNext(); ) {
    String text = it.next();

Then, quoting example 6.4.1 of the JLS:

A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well.

As such, there is no compile-time error here because no restriction is made when shadowing a member variable by a local variable, which is the case here: the local variable String text is shadowing the member variable List<String> text.

Leave a Comment