It prints:
1000
Since testing is done at the bottom of the loop, the loop body must execute at least once, regardless of conditions. Java does not "look ahead" to the condition that is tested. It executes the loop body, then tests the condition to see if it should execute it again.
int count = 1000; // initialize
do
{
System.out.println( count );
count++ ; // change
}
while ( count < 10 ); // test
|
It is easy to mistakenly think that
loop body will not execute even once,
because
count
starts at 1000,
and the test requires count
to be less than 10.
But, in fact,
the loop body does execute once,
printing count
, and then
changing it to 1001 before the test is performed.
This might be a serious bug.
You will save hours of hair-tearing debugging time if you remember that
The body of a do
loop
is always executed at least once.
Almost always there are
situations where a loop body should
not execute, not even once.
Because of this,
a do
loop is
almost always not the appropriate choice.
(Thought question: ) Do you think that a
do
loop is a good choice for a
counting loop?