For Loop

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.

Syntax

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:
  1. any number of statement expressions, separated by comma tokens, or
  2. a local variable declaration.
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...

variable-modifiers is a any number of the modifiers: final or any applicable annotation.
type is the variable's type.
name is an identifier that names the variable.
array-dims is any number of bracket pairs augmenting the array-dimensionality of the type of the variable. Each consecutive [] after the variable name adds a new dimension to the array variable, and can be annotated by an appropriate annotation.
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...

Syntax Elements

1 Basic for loop.

2 Enhanced for loop, looping over an Iterable.

3 Enhanced for loop, looping over an array.

Execution

The execution of enhanced for loops is expressed through a basic for loop.

Basic For Loop Execution

Normal execution (no exceptions, return statements, breaks, etc.) of a basic for loop proceeds as follows. Steps 2, 3, and 4 are repeated until condition evaluates to false.

  1. The init-expression is executed.
  2. The condition is evaluated. If it evaluates to false, the loop is exited.
  3. The body-stmt is executed.
  4. The increment-expr is executed.

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.

Enhanced For Loop Execution

An enhanced for loop is executed by performing the following for each element in an Iterable or an array:

  1. iter-variable-decl is declared and initialized to the current element.
  2. The body-statement is executed. (It may reference iter-variable-decl.)

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:

and an enhanced for loop over an array is equivalent to the following code block:

Show code that is equivalent to enhanced for loop on array.

An enhanced for loop

Abrupt Completion of For Loops

Unlabeled breaks & continues

If execution of the body-statement completes abruptly due to an:

Other Abrupt Completion

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:
  1. init-expression,
  2. condition,
  3. increment-expr, and
  4. body-statement.

The two statements/expressions immediately enclosed by an enhanced for loop are the:

  1. iterable-expr or array-expr, and
  2. body-statement.

Examples

Simple Usage

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

Statement Expression Examples

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
Add enhanced for loop example with non-intuitive expression as the iterable-expr or array-expr.