Java: 'for' Statement
Purpose
The purpose of the for
statement is to repeat
Java statements many times. It is similar to the while
statement, but it is often easier to use if you are counting or indexing
because it combines three elements of many loops: initialization, testing,
and incrementing.
General Form
The for
statement has this form:
for (init-stmt; condition; next-stmt) {
do this each time
}
There are three parts in the for
statement.
- The init-stmt statement is done before the loop is started, usually to initial a variable.
- The condition expression is tested at the beginning of each time
the loop is done. The loop is stopped when this boolean expression
is false (the same as the
while
loop).
- The next-stmt statement is done at the end of every time through the loop,
and usually increments a variable.
Example
Here is a loop written as both a while
loop and
a for
loop. First using while
:
count = 0;
while (count < 50) {
g.drawLine(20, count*5, 80, count*5);
count = count + 1;
}
g.drawString("Loop is finished. count="+count, 10, 300);
And here is the same loop using for
:
for (count=0; count < 50; count = count+1) {
g.drawLine(20, count*5, 80, count*5);
}
g.drawString("Loop is finished. count="+count, 10, 300);
Notice that the for
loop is much shorter. It is better
when you are counting something. Later you will see examples where the
while
loop may be the better choice.