Java Reference
In-Depth Information
A
for
loop is used to repeat a statement until a condition is met. Although
for
loops fre-
quently are used for simple iteration in which a statement is repeated a certain number of
times,
for
loops can be used for just about any kind of loop.
The
for
loop in Java looks roughly like the following:
for (
initialization
;
test
;
increment
) {
statement
;
}
The start of the
for
loop has three parts:
initialization
is an expression that initializes the start of the loop. If you have a
loop index, this expression might declare and initialize it, such as
int i = 0
.
Variables that you declare in this part of the
for
loop are local to the loop itself;
they cease to exist after the loop is finished executing. You can initialize more than
one variable in this section by separating each expression with a comma. The state-
ment
int i = 0, int j = 10
in this section would declare the variables
i
and
j
,
and both would be local to the loop.
n
test
is the test that occurs before each pass of the loop. The test must be a
Boolean expression or a function that returns a
boolean
value, such as
i < 10
. If
the test is
true
, the loop executes. When the test is
false
, the loop stops execut-
ing.
n
increment
is any expression or function call. Commonly, the increment is used to
change the value of the loop index to bring the state of the loop closer to returning
false
and stopping the loop. The increment takes place after each pass of the loop.
Similar to the
initialization
section, you can put more than one expression in
this section by separating each expression with a comma.
n
The
statement
part of the
for
loop is the statement that is executed each time the loop
iterates. As with
if
, you can include either a single statement or a block statement. The
previous example used a block because that is more common. The following example is
a
for
loop that sets all slots of a
String
array to the value
Mr.
:
String[] salutation = new String[10];
int i; // the loop index variable
for (i = 0; i < salutation.length; i++)
salutation[i] = “Mr.”;
In this example, the variable
i
serves as a loop index; it counts the number of times the
loop has been executed. Before each trip through the loop, the index value is compared