15.4. The Enhanced for Statement

The enhanced for statement has the form

Enhanced For Statement
[39]EnhancedForStatement::=for '(' Iterator ')' Statement  
[40]Iterator::=[ [ Modifiers Type ] Identifier ':' ] StatementExpression  

It is used to iterate over finish iterators, iterable objects, arrays, or the sequentially yielded values (Section 16.1, “Generator Expressions and Sequential Evaluation”) of the expression. The distinction is based on the type I of the expression, its potential iteration type, and the specified type and identifier, if any:

If no type has been specified explicitly in the enhanced for statement, or if the potential iteration type is assignable to the explicitly specified type, then the actual iteration and type are the potential iteration and type, otherwise the actual iteration is over the sequentially yielded values of the expression, and the actual iteration type is I.

If an identifier v is specified in the enhanced for statement, a local variable of that name is declared. Its scope is the contained statement. It is a compile-time error if there exists a local variable of the given name in the current scope. The type T and modifiers m of the local variable are the given type and modifiers, or the actual type and final if no type is specified. It is a compile-time error if the actual type is not assignable to the type of the variable.

Let e be the expression of the enhanced for statement and s the contained statement, then the execution of the statement is as follows:

In the above definitions, the #-prefixed identifiers are compiler-generated identifiers that are distinct from any other identifier.