do-while Loop
A do-while loop runs its body first and checks the condition afterward, guaranteeing at least one execution — the natural fit for menus, retries, and validation prompts.
A do-while loop is a post-test loop: it executes the body once, then checks the condition, and repeats only if that condition is true. Because the check happens after the body, a do-while loop always runs at least once, no matter what the condition evaluates to.
What Is a do-while Loop
The syntax is do { body } while (condition); — note the semicolon after the closing parenthesis, which is required and easy to forget.
int count = 0;
do {
System.out.println("count = " + count);
count++;
} while (count < 3);
// count = 0
// count = 1
// count = 2Post-Test: Condition Checked After the Body
Unlike while and for, which check their condition before the first iteration, do-while checks it after the body has already run once. This is the loop's defining feature and the reason to reach for it.
Execution order: run body -> check condition -> if true, run body again -> check condition -> ... -> stop when condition is false.
Guaranteed At Least One Execution
Even if the condition would be false from the start, a do-while loop's body still runs exactly once before that condition is ever evaluated.
Compare with while, where the equivalent condition being false from the start means the body never runs at all — this is the concrete behavioral difference that should drive the choice between the two.
int n = 100;
do {
System.out.println("This runs even though n is already 100: n = " + n);
} while (n < 10); // false immediately, but too late - body already ranPractical Use Cases
do-while fits naturally whenever the task inherently must happen at least once before you can even know whether to repeat it: displaying a menu and reading a choice, prompting for input and then validating it, or retrying an operation where you always attempt it at least once.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1) Start 2) Settings 3) Quit");
choice = scanner.nextInt();
if (choice < 1 || choice > 3) {
System.out.println("Invalid choice, try again.");
}
} while (choice < 1 || choice > 3);
System.out.println("You picked: " + choice);Input Validation Pattern
A very common do-while idiom is: attempt to read/validate input, and if it's invalid, loop back and ask again. The body must run at least once because you have to attempt the read before you can know whether it was valid.
Scanner scanner = new Scanner(System.in);
int age;
do {
System.out.print("Enter your age (0-120): ");
age = scanner.nextInt();
} while (age < 0 || age > 120);do-while vs while: Choosing Between Them
Ask: does the task need to happen before I can even evaluate the condition? If yes, do-while fits. If the condition can meaningfully be checked before doing anything at all — e.g. "is the list empty?" before processing it — while (or for) is the better and more common fit. In everyday Java code, while and for are used far more often than do-while, precisely because most loop conditions can be sensibly checked up front.
// while: fine to check before doing anything
while (queue.hasNext()) {
process(queue.next());
}
// do-while: the action (reading a choice) has to happen before you can validate it
do {
choice = readChoice();
} while (!isValid(choice));Nested do-while Loops
do-while loops nest the same way for and while loops do; each level runs its body at least once regardless of the outer loop's state.
int i = 0;
do {
int j = 0;
do {
System.out.println(i + "," + j);
j++;
} while (j < 2);
i++;
} while (i < 2);Edge Cases
Because the body always runs at least once, a do-while loop can have observable side effects (printing, mutating state, incrementing counters) even when the surrounding logic "looks like" it should never execute. Reviewers unfamiliar with this loop type sometimes miss this and assume a false-looking condition means no execution at all.
As with while and for, if nothing inside the body changes the variables the condition depends on, the loop never terminates — the post-test structure does not exempt do-while from that requirement.
Complete Example
The player must guess at least once before the game can know whether to stop, which is exactly what do-while models.
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int secret = 42;
int guess;
int attempts = 0;
do {
System.out.print("Guess the number: ");
guess = scanner.nextInt();
attempts++;
if (guess < secret) {
System.out.println("Too low.");
} else if (guess > secret) {
System.out.println("Too high.");
}
} while (guess != secret);
System.out.println("Correct! It took " + attempts + " attempts.");
}
}Mental Model
Think of do-while as "do it, then decide whether to do it again" — the opposite order from while's "decide whether to do it, then do it." The body is never optional on the first pass; only later repeats are conditional.
Quick Reference
do {
body
} while (condition); // semicolon required
condition checked AFTER each iteration
body always runs at least once
Use when: the action must happen before the stopping condition can be evaluated
(menus, input validation, retry-at-least-once patterns).Key Takeaways
do-while checks its condition after the body runs, guaranteeing at least one execution.
The trailing while (condition); requires a semicolon, unlike a for or while header.
It fits situations where the action must happen before you can even evaluate whether to repeat — menus, prompts, and validation loops.
The loop still needs something inside the body to change the condition's outcome, or it runs forever just like while and for.
while and for are used far more often in everyday code; reach for do-while specifically when "at least once" is the natural requirement.
do { System.out.println("hi"); } while (false) do { System.out.println("hi"); } while (false);
The semicolon after the while(condition) in a do-while statement is mandatory; omitting it is a compile error, unlike a plain while or for loop's header.
int n = 0; do { // process nothing since n could be 0 items } while (n < items.size());
int n = 0; while (n < items.size()) { // process item n n++; } do-while always runs its body at least once, even when the collection is empty and there's nothing meaningful to do; when zero iterations is a valid, expected outcome, a plain while loop is the correct choice.
int attempts = 0; do { attempt(); } while (attempts < 3); // attempts never updated int attempts = 0; do { attempt(); attempts++; } while (attempts < 3);
Just like any other loop, do-while needs its condition's dependencies updated inside the body; forgetting to increment attempts here creates an infinite loop.
How many times does a do-while loop's body run if the condition is false from the very start?
Exactly once — the body always executes before the condition is checked for the first time.
What punctuation is required after the condition in a do-while statement that isn't required after a while loop's header?
A trailing semicolon: do { ... } while (condition); — omitting it is a compile error.
Why is do-while a good fit for a menu-driven console program?
The menu has to be shown and a choice read at least once before you can know whether the choice was valid or whether the user wants to quit, which matches do-while's "run first, check after" structure.
When is do-while a poor choice compared to while?
When zero iterations is a valid, expected outcome — for example, processing items in a possibly-empty collection — since do-while would force at least one iteration even when there's nothing to process.
What is the fundamental structural difference between while and do-while in terms of when the condition is checked?
while checks the condition before the body runs (pre-test); do-while checks it after the body runs (post-test) — that ordering is the only structural difference, but it changes the minimum guaranteed number of iterations from zero to one.
Does do-while exempt you from having to update the condition's dependent variables inside the loop body?
No — exactly like while and for, if nothing inside the body changes what the condition depends on, the loop will never terminate.
In everyday Java code, is do-while used more or less often than while and for?
Less often — most loop conditions can be sensibly evaluated before doing any work, which is what while and for are naturally suited for; do-while is reserved for the specific case where the action must happen before the condition can even be evaluated.
Write a do-while loop that prompts (simulate with a fixed array of inputs) until a positive number is entered, using a simple counter to simulate input instead of Scanner.
int[] simulatedInputs = {-5, -1, 0, 7}; int idx = 0; int value; do { value = simulatedInputs[idx]; idx++; } while (value <= 0); System.out.println("First positive value: " + value);
The loop keeps pulling from simulatedInputs and re-checking until it reads a value greater than 0 (7), printing that as the result; it must read at least once before it can check anything, which is exactly the do-while pattern.
What does this print, and why?
1 — even though x > 10 is false immediately (x starts at 5), the body still runs once before the condition is checked, decrementing x to 4 and incrementing count to 1, then the loop stops.
Write a do-while loop that repeatedly halves an integer n until it becomes 0, counting how many halvings occurred, starting from n = 1 (so it still runs once).
int n = 1; int halvings = 0; do { n = n / 2; halvings++; } while (n > 0); System.out.println(halvings);
n starts at 1; the body runs once (n becomes 0, halvings becomes 1), then the condition n > 0 is false, so the loop stops after exactly 1 halving.
What does this print, and why does it only print once?
It prints "10 " and then stops, because the body runs unconditionally the first time (printing 10, then i becomes 15), and only afterward is the condition i < 10 checked — which is false since i is now 15 — so the loop exits after a single iteration.
int x = 5;
int count = 0;
do {
x--;
count++;
} while (x > 10);
System.out.println(count);int i = 10;
do {
System.out.print(i + " ");
i += 5;
} while (i < 10);