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.