Here is a full program showing all the important behaviours together.
final int LIMIT = 3;
final int START_ALREADY_DONE = 10;
// step one: the basic do-while
int count = 0;
do {
System.out.println("Pass " + count);
count++;
} while (count < LIMIT);
// step two: the zero-iteration proof. The body runs even
// though the condition is false from the very first test.
int alreadyDone = START_ALREADY_DONE;
do {
System.out.println("This still runs once, alreadyDone is " + alreadyDone);
alreadyDone++;
} while (alreadyDone < LIMIT);
The second part is the one to internalise. If you delete the do and turn it into a plain while loop, that print statement disappears completely, because the condition is false before the first test. Same condition, same starting value, completely different behaviour.
For the wider picture across all four loops, see the looping overview page. For the two-way version of this comparison, see if...else for two-way decisions.
Frequently Asked Questions
What is an exit-controlled loop?
A loop that tests its condition after running the body, so the body always executes at least once. A do-while loop is the standard example. It is the opposite of an entry-controlled loop such as a for or while loop.
Why does do-while need a semicolon?
Because the condition is a separate clause that follows the block, and the semicolon terminates that clause. An if, for or while loop is complete at its closing brace, but a do-while is not, which makes it the only loop in Java that requires a trailing semicolon.
When should I use do-while instead of while?
When the body must happen at least once regardless, such as displaying a menu before reading a choice or asking for one value before validating it. If the work should be skipped entirely when there is nothing to do, use a plain while loop.
Can a do-while loop run forever?
Yes. The one-pass guarantee says nothing about stopping. As with any loop, something inside the body must move the condition toward false, otherwise the loop runs forever after that first pass.
What happens if I use do-while on an empty collection?
The body runs once even though there is nothing to process, because the guarantee applies regardless of the data. Use a for-each loop when an empty collection should mean no iterations at all.
Is do-while faster than while?
No, they compile to effectively the same code. Choose based on whether you genuinely need a guaranteed first pass, not on performance.
Can a do-while loop be infinite on purpose?
Yes. Using do { ... } while (true); is a legitimate pattern, useful for a loop that exits through break, a return or an exception rather than through its condition.
Why does my do-while run one extra time?
Because it is designed to. The condition is checked after the body, so the last pass is the one where the condition turns false. If you did not want that pass, you needed a while loop.