Java Do While Loop
The do/while loop is a close cousin of the while loop with one important twist: it always runs the body at least once before it checks the condition. This makes it perfect for situations where you need to do something first and then decide whether to repeat.
How do/while is different
A regular while loop checks the condition at the top, so if the condition is false from the start, the body never runs. A do/while loop flips that order. It runs the body first and checks the condition at the bottom, guaranteeing at least one execution.
Basic do/while syntax
int i = 0;
do {
System.out.println("Value: " + i);
i++;
} while (i < 3);
// Output:
// Value: 0
// Value: 1
// Value: 2When at-least-once matters
Compare the two loops below. Both have a condition that is false right away, but they behave very differently. The while loop prints nothing, while the do/while loop still prints one line because its check happens after the body.
Same false condition, different result
int n = 10;
while (n < 5) {
System.out.println("while ran");
}
do {
System.out.println("do/while ran once");
} while (n < 5);
// Output:
// do/while ran onceThis is why do/while fits menus and prompts so well: you want to show the menu at least once, then repeat only if the user has not chosen to quit.
- The body runs before the condition is ever tested.
- It is ideal for input validation and menu screens.
- You still need an update step to avoid an infinite loop.
- The condition line ends with a semicolon.