5.9 Do While

This lesson covers the Java do/while loop. It is very similar to the while loop we used earlier, with one important difference: the condition is placed at the end of the block, after the closing brace. Because of that placement, the body of the loop is always executed at least once, even if the condition turns out to be false right away.

The same counter, written with do-while

We initialise a counter int count = 1; and we print a separator so we can tell this output apart from the while and for versions. The loop itself looks like this:

do {
    System.out.println("count value is " + count);
    count++;
} while (count != 6);

On the first iteration the body runs unconditionally, then the condition count != 6 is evaluated. As long as it is true, we loop again. When it becomes false the loop exits. Running this snippet produces the same output as the while and for equivalents.

  • Initialisation: prepares the variable used inside the loop.
  • Condition: evaluated at the end of the block instead of at the start.
  • Increment: keeps the loop moving toward termination.

Choose do/while when the body must run at least once, for example when asking a user for input until they provide something valid. In every other case, a regular while or for is usually clearer.

Summary

The do-while loop is a repetition control structure that evaluates its condition at the end of the loop block, guaranteeing at least one execution. Unlike the while loop where the condition is checked first, do-while shares the same structure of initialization, condition testing, and increment expressions as for and while loops, but differs in the timing of the condition evaluation.

Key points

  • Do-while is a repetition structure where the condition is evaluated at the END of the loop block
  • The loop executes at least once because the condition check happens after the first iteration
  • Shares three common parts with for/while: initialization, condition expression, and increment expression
  • Useful when the code block must execute at least once regardless of the initial condition
  • Syntax structure: do { /* code block */ } while(condition)
  • Condition must become false to exit the loop, just like other loop types

FAQ

What is the key difference between do-while and while loops?

In do-while, the condition is evaluated at the end of the loop block, so the loop body always executes at least once. In while, the condition is checked first, so the loop may not execute at all if the condition is false.

What are the three parts of a do-while loop structure?

Initialization (setting up the loop variable), condition expression (checked at the end of each iteration), and increment expression (updating the variable after each loop execution).

When should I use a do-while loop instead of a while loop?

Use do-while when you need the code block to execute at least once, even if the condition would be false on the first check.