The for statement has two forms:
- The basic
forstatement. - The enhanced
forstatement
ForStatement:
BasicForStatement
EnhancedForStatement
ForStatementNoShortIf:
BasicForStatementNoShortIf
EnhancedForStatementNoShortIf
14.14.1. The basic for Statement
The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
BasicForStatementNoShortIf:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression {, StatementExpression}
The type of the Expression must be boolean or Boolean, or a compile-time error occurs.
The scope and shadowing of a local variable declared in the ForInit part of a basic for statement is specified in §6.3 and §6.4.
References to a local variable declared in the ForInit part of a basic for statement from a nested class or interface, or a lambda expression, are restricted, as specified in §6.5.6.1.
14.14.1.1. Initialization of for Statement
A for statement is executed by first executing the ForInit code:
-
If the ForInit code is a list of statement expressions (§14.8), the expressions are evaluated in sequence from left to right; their values, if any, are discarded.
If evaluation of any expression completes abruptly for some reason, the
forstatement completes abruptly for the same reason; any ForInit statement expressions to the right of the one that completed abruptly are not evaluated. -
If the ForInit code is a local variable declaration (§14.4), it is executed as if it were a local variable declaration statement appearing in a block (§14.4.2).
If execution of the local variable declaration completes abruptly for any reason, the
forstatement completes abruptly for the same reason. -
If the ForInit part is not present, no action is taken.
14.14.1.2. Iteration of for Statement
Next, a for iteration step is performed, as follows:
-
If the Expression is present, it is evaluated. If the result is of type
Boolean, it is subjected to unboxing conversion (§5.1.8).If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly, the
forstatement completes abruptly for the same reason.Otherwise, there is then a choice based on the presence or absence of the Expression and the resulting value if the Expression is present; see next bullet.
-
If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is
true, then the contained Statement is executed. Then there is a choice:-
If execution of the Statement completes normally, then the following two steps are performed in sequence:
-
First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the
forstatement completes abruptly for the same reason; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated.If the ForUpdate part is not present, no action is taken.
-
Second, another
foriteration step is performed.
-
-
If execution of the Statement completes abruptly, see §14.14.1.3.
-
-
If the Expression is present and the value resulting from its evaluation (including any possible unboxing) is
false, no further action is taken and theforstatement completes normally.If the (possibly unboxed) value of the Expression is
falsethe first time it is evaluated, then the Statement is not executed.
If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.
14.14.1.3. Abrupt Completion of for Statement
Abrupt completion of the contained Statement is handled in the following manner:
-
If execution of the Statement completes abruptly because of a
breakwith no label, no further action is taken and theforstatement completes normally. -
If execution of the Statement completes abruptly because of a
continuewith no label, then the following two steps are performed in sequence:-
First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded.
If the ForUpdate part is not present, no action is taken.
-
Second, another
foriteration step is performed.
-
-
If execution of the Statement completes abruptly because of a
continuewith labelL, then there is a choice:-
If the
forstatement has labelL, then the following two steps are performed in sequence:-
First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded.
If the ForUpdate is not present, no action is taken.
-
Second, another
foriteration step is performed.
-
-
If the
forstatement does not have labelL, theforstatement completes abruptly because of acontinuewith labelL.
-
-
If execution of the Statement completes abruptly for any other reason, the
forstatement completes abruptly for the same reason.Note that the case of abrupt completion because of a
breakwith a label is handled by the general rule for labeled statements (§14.7).
14.14.2. The enhanced for statement
The enhanced for statement has the form:
EnhancedForStatement:
for ( LocalVariableDeclaration : Expression ) Statement
EnhancedForStatementNoShortIf:
for ( LocalVariableDeclaration : Expression ) StatementNoShortIf
The following productions from §4.3, §8.3, §8.4.1, and §14.4 are shown here for convenience:
LocalVariableDeclaration:
{VariableModifier} LocalVariableType VariableDeclaratorList
VariableModifier:
Annotation
final
LocalVariableType:
UnannType
var
VariableDeclaratorList:
VariableDeclarator {, VariableDeclarator}
VariableDeclarator:
VariableDeclaratorId [= VariableInitializer]
VariableDeclaratorId:
Identifier [Dims]
_
Dims:
{Annotation} [ ] {{Annotation} [ ]}
The type of the Expression must be an array type (§10.1) or a subtype of the raw type Iterable, or a compile-time error occurs.
The header of the enhanced for statement either declares a local variable whose name is the identifier given by VariableDeclaratorId, or declares an unnamed local variable (§6.3). When the enhanced for statement is executed, the local variable is initialized, on each iteration of the loop, to successive elements of the Iterable or the array produced by the expression.
The rules for a local variable declared in the header of an enhanced for statement are specified in §14.4, disregarding any rules in that section which apply when the LocalVariableType is var. In addition, all of the following must be true, or a compile-time error occurs:
- The VariableDeclaratorList consists of a single VariableDeclarator.
- The VariableDeclarator has no initializer.
- The VariableDeclaratorId has no bracket pairs if the LocalVariableType is
var.
The scope and shadowing of a local variable declared in the header of an enhanced for statement is specified in §6.3 and §6.4.
References to the local variable from a nested class or interface, or a lambda expression, are restricted, as specified in §6.5.6.1.
The type T of the local variable declared in the header of the enhanced for statement is determined as follows:
-
If the LocalVariableType is UnannType, and no bracket pairs appear in UnannType or VariableDeclaratorId, then T is the type denoted by UnannType.
-
If the LocalVariableType is UnannType, and bracket pairs appear in UnannType or VariableDeclaratorId, then T is specified by §10.2.
-
If the LocalVariableType is
var, then let R be derived from the type of the Expression, as follows:- If the Expression has an array type, then R is the component type of the array type.
- Otherwise, if the Expression has a type that is a subtype of
Iterable<X>, for some type X, then R is X. - Otherwise, the Expression has a type that is a subtype of the raw type
Iterable, and R isObject.
T is the upward projection of R with respect to all synthetic type variables mentioned by R (§4.10.5).
The precise meaning of the enhanced for statement is given by translation into a basic for statement, as follows:
-
If the type of Expression is a subtype of
Iterable, then the basicforstatement has this form:for (I #i = Expression.iterator(); #i.hasNext(); ) { {VariableModifier} T VarDeclId = (TargetType) #i.next(); Statement }where:
- If the type of Expression is a subtype of
Iterable<X>for some type argument X, then I is the typejava.util.Iterator<X>. Otherwise, I is the raw typejava.util.Iterator. #iis an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope (§6.3) at the point where the enhancedforstatement occurs.- {VariableModifier} is as given in the header of the enhanced
forstatement. - T is the type of the local variable as determined above.
- If T is a reference type, then TargetType is T. Otherwise, TargetType is the upper bound of the capture conversion (§5.1.10) of the type argument of I, or
Objectif I is raw. - If the declaration of a local variable in the header includes an identifier then VarDeclId is defined to be Identifier as given in the header; otherwise VarDeclId is defined to be
_(underscore).
- If the type of Expression is a subtype of
-
Otherwise, the Expression necessarily has an array type, S
[], and the basicforstatement has this form:S[] #a = Expression; L_1: L_2: ... L_m: for (int #i = 0; #i < #a.length; #i++) { {VariableModifier} T VarDeclId = #a[#i]; Statement }where:
L_1...L_mis the (possibly empty) sequence of labels immediately preceding the enhancedforstatement.#aand#iare automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhancedforstatement occurs.- {VariableModifier} is as given in the header of the enhanced
forstatement. - T is the type of the local variable as determined above.
- If the declaration of a local variable in the header includes an identifier then VarDeclId is defined to be Identifier as given in the header; otherwise VarDeclId is defined to be
_(underscore).
For example, this code:
List<? extends Integer> l = ...
for (float i : l) ...
will be translated to:
for (Iterator<Integer> #i = l.iterator(); #i.hasNext(); ) {
float #i0 = (Integer)#i.next();
...
Example 14.14-1. Enhanced for And Arrays
The following program, which calculates the sum of an integer array, shows how enhanced for works for arrays:
int sum(int[] a) {
int sum = 0;
for (int i : a) sum += i;
return sum;
}
Example 14.14-2. Enhanced for And Unboxing Conversion
The following program combines the enhanced for statement with auto-unboxing to translate a histogram into a frequency table:
Map<String, Integer> histogram = ...;
double total = 0;
for (int i : histogram.values())
total += i;
for (Map.Entry<String, Integer> e : histogram.entrySet())
System.out.println(e.getKey() + " " + e.getValue() / total);
}