更新时间:2022-10-14 23:05:29
While the reasoning, using the specified translation from the enhanced for
loop to the traditional for
loop, used by other answers is correct, there is an explicit specification about the scopes:
§6.3. Scope of a Declaration
…
The scope of a local variable declared in the FormalParameter part of an enhanced
for
statement (§14.14.2) is the contained Statement.
Thus, the scope of the variable does not include the Expression of the enhanced for
loop…
You can verify that this hasn’t changed, compared to Java 7
and Java 6,
though both (I tried Java 6 javac
) exhibit the contradicting behavior.
So this change in the compiler behavior is the fix of an old bug…