The Do Statement
The 'do-while' loop is a variation of the while loop. 'do-while' loops always execute at least once, whereas while loops may never execute.
4. Loop Body is Always Executed at Least Once
Answer:
It prints:
1000
Loop Body is Always Executed at Least Once
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 changes 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.
Question 4:
(Thought question: ) Do you think that a do
loop is a good choice for a counting loop?