A looping statement used to repeatedly execute another statement (the body statement) in a structured manner.
For loops come in two forms: Basic and Enhanced.
Basic for loops contain an initializer expression, a condition, an
increment expression, and a body statement. They are executed beginning
with their initializer statement. Then the condition is evaluated and,
while it's true
, the body statement and then the increment
expression are executed, in that order. The condition, body, and
increment expression are executed repeatedly until the condition
evaluates to false
or the for loop structure completes
abruptly.
Enhanced for loops execute their body statement for every member of an
Iterable
or an array type expression. An enhanced for loop
is said to loop over the Iterable
or array.
For Loops have three forms:
1 | for ( init-expression
; condition ;
increment-expr )
body-statement |
2 | for ( iter-variable-decl
: iterable-expr )
body-statement |
3 | for ( iter-variable-decl
: array-expr )
body-statement |
where...
init-expression | is either:
|
||||||||
condition | is an expression of type boolean or Boolean .
|
||||||||
increment-expr | is any number of statement expressions, separated by comma tokens. | ||||||||
body-statement | is any statement. | ||||||||
iter-variable-decl | is a formal parameter declaration, (as in a method declaration's
parameter list). Equivalently, the iter-variable-decl
is a local variable declaration without the optional initializer (and
without the trailing semicolon):
variable-modifiers type name
array-dims
where...
|
||||||||
iterable-expr | is any expression that is assignable to the Iterable
type. Iterable is generic; the type of the expression
may be either raw or parameterized.
|
||||||||
array-expr | is any expression whose type is an array type. |
such that...
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
Dog[] dogArray = new Dog[100]; // Each element has type Dog
// Valid enhanced for loops:
for (Dog d : dogArray); // Dog objects (from the array) can fit in the Dog variable, d
for (Animal a : dogArray); // Dog objects can fit in the Animal variable, a
for (Object o : dogArray); // Dog objects can fit in the Object variable, o
// Invalid enhanced for loops:
// for (Cat c : dogArray); // Invalid; Dog objects cannot fit in Cat variable, c
1 Basic for
loop.
2 Enhanced for
loop,
looping over an Iterable
.
3 Enhanced for
loop,
looping over an array.
The execution of enhanced for
loops is expressed through a
basic for
loop.
Normal execution (no exceptions, return
statements, break
s,
etc.) of a basic for
loop proceeds as follows. Steps 2, 3, and 4 are repeated until condition evaluates to false
.
false
, the loop is
exited.
The loop exits normally if the condition
evaluates to false
.
Each of the statement expressions in the increment-expr is executed in the order they are written. If any statement expression completes abruptly, the whole increment-expr immediately completes abruptly for the same reason. If the init-expression is also a list of statement expressions, it is executed in the same way.
An enhanced for loop is executed by performing the following for each
element in an Iterable
or an array:
These steps comprise one iteration of an enhanced for loop. Each
iteration is performed synchronously, in order, and elements of the Iterable
or array are retrieved in natural order (first to last). More formally,
an enhanced for loop over an Iterable
is equivalent to the
following code block:
{
IterableType iterable = iterable-expr;
while (iterable.hasNext()) {
iter-variable-decl = (ItemType) iterable.next();
body-statement
}
}
where:
iterable
is a unique variable name,IterableType
is the type of the iterable-expr, andItemType
is:
Object
, if IterableType
is a
raw type, otherwise,
IterableType
.
and an enhanced for loop over an array is equivalent to the following code block:
An enhanced for loop
break
s & continue
s
If execution of the body-statement completes abruptly due to an:
break
, the for loop immediately
completes normally.continue
, the for loop loops, (as
if the body-statement completed
normally), executing the increment-expr
(step 4 in the list of steps above).Otherwise, if execution of any statement/expression immediately enclosed by a for loop completes abruptly, due to any other reason, the for loop immediately completes abruptly for the same reason.
The four statements/expressions immediately enclosed by a basic for loop are the:The two statements/expressions immediately enclosed by an enhanced for loop are the:
A simple example of a basic for loop used to print the numbers 0 through 4:
for (int i = 0; i < 5; i++)
System.out.println(i);
Output:
0
1
2
3
4
This example demonstrates using a basic for loop to fill the list, strs
,
with values, then using an enhanced for loop to print each value
inside strs
.
List<String> strs = new ArrayList<>();
for (int i = 0; i < 10; i++)
strs.add("Letter: " + (char) (i + 'a'));
for (String s : strs)
System.out.println(s);
Output:
Letter: a
Letter: b
Letter: c
Letter: d
Letter: e
Letter: f
Letter: g
Letter: h
Letter: i
Letter: j
The increment-expr is expressive enough that many for loops can be equivalently written without a body, because basic for loop bodies are often expression statements (like method calls or assignments), which can instead be executed in the increment-expr. For example, the following for loop:
for (int i = 0; i < 5; i++)
System.out.println(i);
can equivalently be written as follows:
for (int i = 0; i < 5; System.out.println(i++))
;
The output of either for loop is as follows:
0
1
2
3
4