Java Reference
In-Depth Information
Figure 3.3 shows the syntax and order of execution of the basic
for
statement.
The syntax of a basic
for
statement
FIGURE 3.3
The for keyword
Semicolons (required)
Parentheses (required)
for(
initialization
;
boolean_expression
;
update_statement
) {
1. The initialization
statement
executes
2. The boolean is checked.
4. The update statement
executes each time
after the body.
3. If the boolean is true, the
body of the loop executes.
5. The boolean is checked
each time after the update
statement. Steps 3-5 repeat
until the boolean is false.
}
Let's look at an example. The following
for
loop displays the numbers 1 to 10:
for(int x = 1; x <= 10; x++) {
System.out.print(x + “ “);
}
The following sequence of events occurs during this loop:
1.
The
int x
is allocated in memory and initialized to
1
.
2.
The
boolean
expression is evaluated.
x
is less than or equal to
10
so the body of the
loop executes.
3.
The print statement displays
1
and a space.
4.
The end of the
for
loop is reached on line 7, so control jumps to the update statement
x++
, incrementing
x
to
2
.
5.
The
boolean
is checked again.
x
is still less than or equal to
10
, so steps 3 and 4 repeat
until
x
is the value
11
.
6.
The
boolean
is now false, so the
for
loop terminates and
x
goes out of scope.
The output of this loop is
1 2 3 4 5 6 7 8 9 10
Search WWH ::
Custom Search