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


It prints:


Loop Body is Always Executed at Least Once

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

  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?