Java Reference
In-Depth Information
in the initialization part that you initialize variables. In the example, you have declared
loopCounter
and set it to the value of
1
. This part is only executed once during the execution of the loops, unlike
the other parts. You don't need to declare the variable if it was declared earlier in the code:
var loopCounter;
for (loopCounter = 1; loopCounter <= 3; loopCounter++)
Initialize loop variable
Loop test condition
Increment loop variable
for ( loopCounter = 1; loopCounter <= 3; loopCounter++)
{
// execute this code
}
Code looped through
figure 3-10
Following the semicolon, you have the
test condition
part of the
for
statement. The code inside
the
for
statement will keep executing for as long as this test condition evaluates to
true
. After the
code is looped through each time, this condition is tested. In Figure 3-10, you execute for as long as
loopCounter
is less than or equal to
3
. The number of times a loop is performed is often called the
number of
iterations
.
Finally, you have the
increment
part of the
for
loop, where variables in your loop's test condition have
their values incremented. Here you can see that
loopCounter
is incremented by one by means of the
++
operator you saw in Chapter 2. Again, this part of the
for
statement is repeated with every loop of
the code. Although we call it the increment part, it can actually be used to decrease, or
decrement
, the
value—for example, if you wanted to count down from the top element in an array to the first.
After the
for
statement comes the block of code that will be executed repeatedly, as long as the
test condition is
true
. This block of code is contained within curly braces. If the condition is never
true
, even at the first test of the loop condition, the code inside the
for
loop will be skipped over
and never executed.
Putting all this together, how does the
for
loop work?
1.
Execute initialization part of the
for
statement.
2.
Check the test condition. If
true
, continue; if not, exit the
for
statement.
3.
Execute code in the block after the
for
statement.
4.
Execute the increment part of the
for
statement.
5.
Repeat steps 2 through 4 until the test condition is
false
.