Java Reference
In-Depth Information
Ask the Expert
Q
:
Given the flexibility inherent in all of Java's loops, what criteria should I use
when selecting a loop? That is, how do I choose the right loop for a specific job?
A
:
Use a
for
loop when performing a known number of iterations. Use the
do
-
while
when you need a loop that will always perform at least one iteration. The
while
is
best used when the loop will repeat an unknown number of times.
The do-while Loop
The last of Java's loops is the
do
-
while
. Unlike the
for
and the
while
loops, in which the
condition is tested at the top of the loop, the
do-while
loop checks its condition at the bot-
tom of the loop. This means that a
do-while
loop will always execute at least once. The
general form of the
do-while
loop is
Although the braces are not necessary when only one statement is present, they are often
used to improve readability of the
do-while
construct, thus preventing confusion with the
while
. The
do-while
loop executes as long as the conditional expression is true.
The following program loops until the user enters the letter q: