Java Reference
In-Depth Information
Figure 5-2.
Execution of a for statement
For example, the following
for
-loop statement will print all integers between 1 and 10, inclusive:
for(int num = 1; num <= 10; num++)
System.out.println(num);
First,
int num = 1
is executed, which declares an
int
variable
num
and initializes it to 1. It is important to note that
variables declared in the initialization part of the
for
-loop statement can only be used within that
for
-loop statement.
Then, condition-expression (
num <= 10
) is evaluated, which is 1 <= 10. It evaluates to
true
for the first time. Now,
the statement associated with the
for
-loop statement is executed, which prints the current value of
num
. Finally, the
expression in the expression-list,
num++
, is evaluated, which increments the value of
num
by 1
.
At this point, the value
of
num
becomes 2. The condition-expression
2 <= 10
is evaluated, which returns
true
, and the current value of
num
is
printed. This process continues until the value of
num
becomes 10 and it is printed. After that,
num++
sets the value of
num
to 11, and the condition-expression
11 <= 10
returns
false
, which stops the execution of the
for
-loop statement.
All three parts (initialization, condition-expression, and expression-list) in a
for
-loop statement are optional.
Note that the fourth part, the statement, is not optional. Therefore, if you do not have a statement to execute in a
for
-loop statement, you must use an empty block statement or a semicolon in place of a statement. A semicolon that
is treated as a statement is called an empty statement or a null statement. An infinite loop using a
for
-loop statement
can be written as follows:
for( ; ; ) { /* An infinite loop */
}
Or
for( ; ; ); /* An infinite loop. Note a semicolon as a statement */
A detailed discussion of each part of a
for
-loop statement follows.