Java Reference
In-Depth Information
Execution of the loop continues as long as the condition you have specified in the second part, the
loop
_
condition
, is
true
. This expression is checked at the beginning of each loop iteration, and
when it is
false
, execution continues with the statement following the loop block. A simple example of
what the
loop
_
condition
expression might be is
i<10
, so the loop would continue in this case as
long as the variable
i
has a value less than 10.
The third part of the control information between the parentheses, the
increment
_
expression
, is
usually used to increment the loop counter. This is executed at the end of each loop iteration. This
could be
i++
, which would increment the loop counter,
i
, by one. Of course, you might want to
increment the loop counter in steps other than 1. For instance, you might write
i
+=
2
as the
increment
_
expression
to go in steps of 2, or even something more complicated such as
i
=
2*i+1
.
2.
The
while
loop:
while (
expression
) {
// statements
}
This loop executes as long as the given logical expression between parentheses is
true
. When
expression
is
false
, execution continues with the statement following the loop block. The
expression is tested at the beginning of the loop, so if it is initially
false
, the loop statement block will
not be executed at all. An example of a
while
loop condition might be,
yesNo=='Y'
||
yesNo=='y'
. This expression would be
true
if the variable
yesNo
contained '
y
' or '
Y
', so
yesNo
might hold a character entered from the keyboard in this instance.
3.
The
do while
loop
do {
// statements
} while (
expression
);
This loop is similar to the
while
loop, except that the expression controlling the loop is tested at the
end of the loop block. This means that the loop block is executed at least once, even if the expression is
always
false
.