Loop Body is Executed at Least Once

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

It prints:

1000

Loop Body is Executed at Least Once

flowchart

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 test. 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

You might expect that the loop body will not execute because count starts at 1000, and the test is count < 10. In fact, the loop body will execute once, and change count to 1001. 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 usually not the appropriate choice.

QUESTION 4:

(Thought question: ) Do you think that a do loop is a good choice for a counting loop?