do-while Loop
The do-while loop is Java’s only post-condition loop — it runs its body first, then checks the condition. This one small difference means the body is guaranteed to execute at least once, no matter what.
Basic Syntax
do {
// body — always runs at least once
} while (condition);
Notice the semicolon after the closing parenthesis. Forgetting it is one of the most common do-while compile errors.
- The body executes first.
- The condition is evaluated after each execution of the body.
- If the condition is
true, the body runs again. Iffalse, the loop ends.
Here is a simple counter:
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
How Execution Flows
The step-by-step order is slightly different from a while loop:
- Body executes.
- Condition is evaluated.
- If
true→ go back to step 1. - If
false→ exit the loop.
Compare this to the while loop, which evaluates the condition before the body — if the condition starts out false, the while body never runs at all. With do-while, at least one execution is always guaranteed.
int x = 100; // condition (x < 5) is already false
do {
System.out.println("do-while ran: x = " + x);
} while (x < 5);
// while loop equivalent — never runs:
while (x < 5) {
System.out.println("while ran: x = " + x);
}
Output:
do-while ran: x = 100
The do-while body ran once even though x < 5 was false from the start. The while loop body was skipped entirely.
Tip: Use
do-whilewhenever you need the body to execute at least once before you can even evaluate a meaningful condition — classic examples include reading user input or displaying a menu.
Classic Use Case: Input Validation
One of the most natural fits for do-while is prompting the user for input and repeating until they enter a valid value:
import java.util.Scanner;
public class InputDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a number between 1 and 10: ");
number = scanner.nextInt();
} while (number < 1 || number > 10);
System.out.println("You entered: " + number);
}
}
You always need to show the prompt and read at least one value before you can check whether it is valid. The do-while makes this intent crystal clear.
Classic Use Case: Menu-Driven Programs
Another perfect fit is a console menu that should display at least once:
import java.util.Scanner;
public class MenuDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Menu ---");
System.out.println("1. Say Hello");
System.out.println("2. Say Goodbye");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Hello!");
case 2 -> System.out.println("Goodbye!");
case 3 -> System.out.println("Exiting...");
default -> System.out.println("Invalid option, try again.");
}
} while (choice != 3);
}
}
The menu must appear before the user can even express a preference — do-while handles that requirement naturally.
do-while with break and continue
You can use break to exit the loop early and continue to skip the rest of the current iteration. With do-while, after a continue the condition is still evaluated before deciding whether to loop again.
int i = 0;
do {
i++;
if (i == 3) continue; // skip printing 3
if (i == 6) break; // stop before 6
System.out.print(i + " ");
} while (i < 10);
Output:
1 2 4 5
Note: After
continue, execution jumps to thewhile (condition)check — not back to the top of the body fromi = 0. The counteriwas already incremented, so there is no infinite loop here.
Nesting do-while Loops
You can nest do-while loops just like any other loop type:
int outer = 1;
do {
int inner = 1;
do {
System.out.print(outer * inner + "\t");
inner++;
} while (inner <= 4);
System.out.println();
outer++;
} while (outer <= 3);
Output:
1 2 3 4
2 4 6 8
3 6 9 12
Choosing the Right Loop
| Loop | Condition checked | Body runs at minimum | Best for |
|---|---|---|---|
for | Before body | 0 times | Known iteration count |
while | Before body | 0 times | Unknown count, may not run |
do-while | After body | 1 time | Must run at least once |
When in doubt: if your code would look like “do X, then keep doing X while Y is true,” reach for do-while. If it is “while Y is true, do X,” a while loop is cleaner.
Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Missing semicolon after while (condition) | Compile error | Always end with }; — i.e. } while (...); |
| Forgetting to update the condition variable inside the body | Infinite loop | Make sure the body modifies what the condition depends on |
Using do-while when the body should sometimes not run | Logic error; body always runs once | Switch to a while loop |
Confusing continue behavior | Skips to condition check, not to top of body before any prior setup | Trace through manually or add a debug print |
// Infinite loop — i never changes!
int i = 0;
do {
System.out.println("Oops, looping forever");
} while (i < 5); // i is never incremented
Warning: Always make sure the loop has a reachable exit: either the condition eventually becomes
false, or abreak/returnis hit inside the body. An infinitedo-whileloop will hang your program.
Under the Hood
Bytecode Translation
The Java compiler compiles do-while into a tight bytecode pattern — there is no dedicated “do-while” instruction. Instead it uses conditional branches:
LABEL_start:
BODY
evaluate CONDITION → boolean
if true → GOTO LABEL_start
LABEL_end:
Compare this to a while loop’s bytecode, which puts an unconditional goto to the condition check before the body label:
GOTO LABEL_condition
LABEL_body:
BODY
LABEL_condition:
evaluate CONDITION → boolean
if true → GOTO LABEL_body
LABEL_end:
The do-while bytecode is one branch shorter — no initial goto to the condition. This makes it very slightly more efficient for the first iteration, though the JIT compiler usually erases any measurable difference for hot loops.
JIT Optimizations
Once the JIT detects a hot do-while loop it applies the same optimizations it would to any loop — loop unrolling, range-check elimination, and induction variable hoisting. See JIT Compilation & Bytecode and How Loops Work (Bytecode & JIT) for the full picture.
Stack Frame Behavior
As with all Java loops, a do-while loop does not create a new stack frame on each iteration. Loop variables live in the method’s local variable table (slots within the current stack frame), making tight loops memory-efficient regardless of iteration count.
Related Topics
- while Loop — pre-condition sibling; the body can run zero times
- for Loop — best when you know the iteration count upfront
- for-each Loop — clean syntax for iterating over arrays and collections
- break Statement — exit any loop early
- continue Statement — skip an iteration and jump to the condition check
- How Loops Work (Bytecode & JIT) — deep dive into how the JVM compiles and optimizes every loop type