Java do-while Loop
Java do-while Loop
The do-while loop is the only Java loop that guarantees the body executes at least once — unconditionally. The condition is checked after the body runs, not before. That single behavioral difference is what makes it the correct choice in a specific set of scenarios where while and for would require awkward workarounds.
Understanding when do-while is genuinely the right tool — rather than forcing while to do the same job with extra code — is what separates a developer who knows syntax from one who thinks about design.
What Is the Java do-while Loop?
The do-while loop is a post-test loop: it executes the body first, then evaluates the condition. If the condition is true, the body runs again. If false, the loop exits. The critical guarantee — the body always runs at least once regardless of what the condition evaluates to — is built into the structure.
This makes do-while the natural fit for:
- ›Menu-driven programs — display the menu once, then repeat based on user choice
- ›Input validation — ask for input at least once, then re-ask until valid input is received
- ›Game loops — run one turn, then check if the game is over
- ›Initialization patterns — perform an action, then check whether to continue
Syntax
Basic do-while
1do {
2 // loop body — always executes at least once
3} while (condition);Note the semicolon after the closing parenthesis. Unlike while and for, the do-while statement requires a semicolon at the end. Forgetting it is a compile-time error.
do-while with break
1do {
2 // loop body
3 if (exitCondition) {
4 break; // exits the loop early without checking the condition
5 }
6} while (condition);Comparison: while vs do-while
1// while — may run zero times
2while (condition) {
3 body();
4}
5
6// do-while — always runs at least once
7do {
8 body();
9} while (condition);The semicolon after while (condition) is unique to do-while. Missing it causes a compile error. This is the most common syntax mistake when switching between loop types.
Beginner Examples
Basic do-while — Guaranteed First Execution
This example shows the defining behavior: the loop body runs even when the condition is initially false.
1public class FirstExecutionDemo {
2
3 public static void main(String[] args) {
4
5 int counter = 10;
6
7 // Condition is false from the start (10 > 0 is true? No — 10 is NOT less than 0)
8 // Wait — let's show a case where condition IS false initially
9 int value = 0;
10
11 // while loop — body never runs because value == 0 is false from the start
12 System.out.println("--- while loop ---");
13 while (value > 0) {
14 System.out.println("while body: " + value);
15 }
16 System.out.println("while loop completed. Body ran zero times.");
17
18 System.out.println("\n--- do-while loop ---");
19 // do-while — body runs once even though value == 0 means condition is false
20 do {
21 System.out.println("do-while body: " + value);
22 } while (value > 0);
23 System.out.println("do-while loop completed. Body ran exactly once.");
24 }
25}Output:
--- while loop ---
while loop completed. Body ran zero times.
--- do-while loop ---
do-while body: 0
do-while loop completed. Body ran exactly once.
The while loop body never ran because value > 0 was false from the start. The do-while body ran once — the body always executes before the condition is evaluated for the first time.
Input Validation — Asking Until Valid Input
This is the most practical everyday use case for do-while in production code.
1import java.util.Scanner;
2
3public class PinValidationDemo {
4
5 public static void main(String[] args) {
6
7 Scanner scanner = new Scanner(System.in);
8 int enteredPin;
9
10 // Ask for PIN at least once, re-ask if invalid
11 // do-while is the natural fit — there is no way to check validity before asking
12 do {
13 System.out.print("Enter 4-digit PIN: ");
14 enteredPin = scanner.nextInt();
15
16 if (enteredPin < 1000 || enteredPin > 9999) {
17 System.out.println("Invalid PIN. Must be a 4-digit number.");
18 }
19
20 } while (enteredPin < 1000 || enteredPin > 9999);
21
22 System.out.println("PIN accepted. Proceeding with verification.");
23 scanner.close();
24 }
25}Using while here would require reading the PIN once before the loop and again inside it — duplicated code. The do-while avoids that duplication by reading inside the body and checking the condition after. This is one of the clearest cases where do-while is genuinely cleaner than the alternatives.
Menu-Driven Program
Menus are a textbook do-while use case: show the menu, process the choice, show again — until the user exits.
1import java.util.Scanner;
2
3public class AccountMenuDemo {
4
5 public static void main(String[] args) {
6
7 Scanner scanner = new Scanner(System.in);
8 int choice;
9
10 do {
11 System.out.println("\n=== Account Menu ===");
12 System.out.println("1. View Balance");
13 System.out.println("2. Transfer Funds");
14 System.out.println("3. Transaction History");
15 System.out.println("4. Exit");
16 System.out.print("Enter choice: ");
17
18 choice = scanner.nextInt();
19
20 switch (choice) {
21 case 1 -> System.out.println("Balance: Rs. 24,500.00");
22 case 2 -> System.out.println("Transfer initiated.");
23 case 3 -> System.out.println("Last 5 transactions displayed.");
24 case 4 -> System.out.println("Logging out.");
25 default -> System.out.println("Invalid choice. Try again.");
26 }
27
28 } while (choice != 4);
29
30 scanner.close();
31 }
32}The menu must always display before the user can make a choice — using while would require displaying it once before the loop, then again inside the body. The do-while keeps the logic in one place and reads exactly like the requirement: show menu, get input, repeat until exit is chosen.
How the do-while Loop Works Internally
Execution Flow
The diagram below shows the precise sequence of events in a do-while loop compared to a while loop.
while loop: do-while loop:
Check condition Execute body
| |
+----+----+ Check condition
| | |
true false +-----+-----+
| | | |
Execute Exit true false
body | |
| Execute Exit
+-- recheck condition body
|
+-- recheck condition
The while loop evaluates the condition on the first pass and may never enter the body. The do-while begins with body execution and evaluates the condition only after the body has run. The paths converge from the second iteration onward — both loops behave identically once the first iteration is complete.
Bytecode Structure
At the JVM bytecode level, a do-while compiles to a body of instructions followed by a conditional backward jump. The while loop compiles to a forward jump to the condition check, the body, and then a backward jump. The do-while generates slightly simpler bytecode because it has no initial forward jump to the condition.
Real-World Example — ATM Transaction Session
The Business Problem
You are building the session management layer for an ATM software system — similar to what NCR or Diebold Nixdorf deploys in Indian bank ATMs. After card insertion and PIN validation, the ATM must display the transaction menu at least once, process the customer's selection, and continue offering the menu until the customer explicitly selects "Exit Session." The ATM must always show the menu before accepting any input — there is no scenario where the menu should be skipped on the first display.
This is a canonical do-while scenario: the action (displaying the menu and processing a transaction) must always happen at least once, and the exit is controlled by user input that cannot be known before the first interaction.
Implementation
1// File: AtmConfig.java
2
3public final class AtmConfig {
4
5 public static final double WITHDRAWAL_LIMIT_PER_TRANSACTION = 10000.0;
6 public static final double DAILY_WITHDRAWAL_LIMIT = 25000.0;
7 public static final int EXIT_OPTION = 4;
8
9 private AtmConfig() {}
10}1// File: AtmSession.java
2
3public class AtmSession {
4
5 private double availableBalance;
6 private double totalWithdrawnToday;
7 private final String cardHolderName;
8
9 public AtmSession(String cardHolderName, double startingBalance) {
10 this.cardHolderName = cardHolderName;
11 this.availableBalance = startingBalance;
12 this.totalWithdrawnToday = 0.0;
13 }
14
15 public String processSelection(int option, double amount) {
16
17 return switch (option) {
18 case 1 -> "Balance: Rs. " + availableBalance;
19
20 case 2 -> {
21 if (amount <= 0) {
22 yield "Invalid amount. Please enter a positive value.";
23 }
24 if (amount > AtmConfig.WITHDRAWAL_LIMIT_PER_TRANSACTION) {
25 yield "Exceeds per-transaction limit of Rs. "
26 + AtmConfig.WITHDRAWAL_LIMIT_PER_TRANSACTION;
27 }
28 if (totalWithdrawnToday + amount > AtmConfig.DAILY_WITHDRAWAL_LIMIT) {
29 yield "Exceeds daily withdrawal limit. Withdrawn today: Rs. "
30 + totalWithdrawnToday;
31 }
32 if (amount > availableBalance) {
33 yield "Insufficient balance.";
34 }
35 availableBalance -= amount;
36 totalWithdrawnToday += amount;
37 yield "Rs. " + amount + " dispensed. Remaining balance: Rs. " + availableBalance;
38 }
39
40 case 3 -> "Mini statement printed for: " + cardHolderName;
41 case 4 -> "Session ended. Card returned. Thank you, " + cardHolderName + ".";
42 default -> "Invalid selection.";
43 };
44 }
45}1// File: AtmDemo.java
2
3public class AtmDemo {
4
5 public static void main(String[] args) {
6
7 AtmSession session = new AtmSession("Karan Mehta", 45000.0);
8
9 // Simulate a sequence of user interactions
10 int[] selections = {1, 2, 2, 3, 4};
11 double[] amounts = {0, 5000.0, 15000.0, 0, 0};
12
13 int interactionIndex = 0;
14 int choice;
15
16 // Menu must display at least once before any choice is possible
17 do {
18 System.out.println("\n=== ATM Menu ===");
19 System.out.println("1. Check Balance");
20 System.out.println("2. Withdraw Cash");
21 System.out.println("3. Mini Statement");
22 System.out.println("4. Exit Session");
23
24 choice = selections[interactionIndex];
25 double requestedAmount = amounts[interactionIndex];
26 interactionIndex++;
27
28 System.out.println("Selection: " + choice);
29 System.out.println(session.processSelection(choice, requestedAmount));
30
31 } while (choice != AtmConfig.EXIT_OPTION);
32 }
33}Output:
=== ATM Menu ===
1. Check Balance
2. Withdraw Cash
3. Mini Statement
4. Exit Session
Selection: 1
Balance: Rs. 45000.0
=== ATM Menu ===
1. Check Balance
2. Withdraw Cash
3. Mini Statement
4. Exit Session
Selection: 2
Rs. 5000.0 dispensed. Remaining balance: Rs. 40000.0
=== ATM Menu ===
1. Check Balance
2. Withdraw Cash
3. Mini Statement
4. Exit Session
Selection: 2
Exceeds per-transaction limit of Rs. 10000.0
=== ATM Menu ===
1. Check Balance
2. Withdraw Cash
3. Mini Statement
4. Exit Session
Selection: 3
Mini statement printed for: Karan Mehta
=== ATM Menu ===
1. Check Balance
2. Withdraw Cash
3. Mini Statement
4. Exit Session
Selection: 4
Session ended. Card returned. Thank you, Karan Mehta.
The withdrawal limit constants live in AtmConfig as named constants. When the RBI updates per-transaction limits, only the config file changes. During code reviews, hardcoded values like 10000.0 or 25000.0 inside loop bodies are consistently flagged — a naming convention that makes the limit's purpose clear is standard practice in financial applications.
Best Practices
Use do-while when the body must run before the first condition check
This is the only reason to choose do-while over while. If you find yourself reading a value once before a while loop and then reading it again inside the body to avoid an initial false condition, that is the signal to switch to do-while.
1// Awkward with while — input read twice, duplicated logic
2String input = scanner.nextLine(); // first read outside loop
3while (!isValid(input)) {
4 System.out.println("Invalid. Try again.");
5 input = scanner.nextLine(); // second read inside loop — duplication
6}
7
8// Clean with do-while — input read once inside the body
9String input;
10do {
11 System.out.println("Enter value:");
12 input = scanner.nextLine(); // single read inside the loop
13} while (!isValid(input));Always remember the semicolon after the while clause
The semicolon at the end of } while (condition); is mandatory and unique to this loop form. It is easy to forget after writing while loops and for loops where no trailing semicolon appears.
Keep the loop body focused — avoid complex multi-responsibility loops
When a do-while body grows beyond fifteen to twenty lines, extract the body logic into a method. The loop header should express the loop's intent; the method expresses what each iteration does.
Common Mistakes
Mistake 1 — Missing the Semicolon After the while Clause
1// This is a compile-time error — missing semicolon
2do {
3 System.out.println("Processing...");
4} while (condition) // missing semicolon here causes compile failureThe compiler produces an error on the line after the while clause because it expects a semicolon to terminate the statement. This mistake is unique to do-while — neither while nor for have a trailing semicolon.
Mistake 2 — Using do-while When the Body Might Not Need to Run
1public class WrongLoopChoiceDemo {
2
3 public static void main(String[] args) {
4
5 // Suppose the list might be empty and no processing should happen
6 java.util.List<String> pendingTasks = java.util.List.of(); // empty list
7
8 int taskIndex = 0;
9
10 // Using do-while here causes ArrayIndexOutOfBoundsException
11 // because the body runs once before checking if there are any tasks
12 do {
13 // taskIndex 0 on an empty list causes IndexOutOfBoundsException
14 String task = pendingTasks.get(taskIndex);
15 System.out.println("Processing: " + task);
16 taskIndex++;
17 } while (taskIndex < pendingTasks.size());
18 }
19}When the collection might be empty, use while or the enhanced for loop — not do-while. The do-while assumption that "the body must run at least once" breaks when the dataset could legitimately have zero elements.
Mistake 3 — Confusing the Condition Timing
1public class ConditionTimingDemo {
2
3 public static void main(String[] args) {
4
5 int retryCount = 0;
6 int maxRetries = 3;
7
8 // Developer expects the loop NOT to run if retryCount already equals maxRetries
9 // But do-while runs the body first — retryCount is 0 here, so it runs
10 do {
11 System.out.println("Retry attempt: " + retryCount);
12 retryCount++;
13 } while (retryCount < maxRetries);
14
15 System.out.println("Final retry count: " + retryCount);
16 }
17}Output:
Retry attempt: 0
Retry attempt: 1
Retry attempt: 2
Final retry count: 3
The loop ran three times — as expected here. But developers who mistake do-while for a while loop are often surprised when the body executes even though they expected the condition to prevent it. The rule is simple: if the condition could be false before the first iteration and the body should not run in that case, use while, not do-while.
Mistake 4 — Infinite Loop from Condition That Never Becomes False
1// Missing update inside the body — condition never becomes false
2int page = 1;
3
4do {
5 System.out.println("Loading page: " + page);
6 // page is never incremented — this runs forever
7} while (page <= 10);The same mistake as infinite while loops applies to do-while: if the condition variable is never modified inside the body, the condition can never become false. The fix is always the same — ensure the condition variable changes during each iteration.
Interview Questions
Q1. What is the key difference between a while loop and a do-while loop in Java?
The primary difference is when the condition is evaluated. A while loop checks the condition before the body runs — if false initially, the body never executes. A do-while loop runs the body first and checks the condition after — the body always executes at least once. This behavioral difference is the entire reason do-while exists: for scenarios where at least one iteration must always occur regardless of the starting state.
Q2. When should you choose do-while over while in Java?
Choose do-while when the loop body must execute at least once before the condition is meaningful — typically because the condition depends on something that happens inside the body. Classic cases are input validation (you must read input before you can validate it), menu-driven programs (the menu must display before the user can make a choice), and initialization loops where an action must be performed before its result can be checked. When the body might legitimately need to run zero times, use while.
Q3. What is the syntax rule unique to do-while that does not apply to while or for?
The do-while loop requires a semicolon after the closing parenthesis of the condition: } while (condition);. No other loop construct in Java requires this. Forgetting the semicolon causes a compile-time error. This is the most common syntax mistake when writing do-while loops, especially when switching from while or for syntax.
Q4. How does the do-while loop differ from the for loop?
The for loop is designed for situations where the iteration count is known before the loop starts — it uses a counter managed in the header. The do-while loop is for situations where the termination condition depends on runtime state and the body must run at least once. A for loop may run zero times if the initial condition is false; a do-while always runs at least once. For user interaction loops and input validation, do-while is the natural fit that for cannot express cleanly.
Q5. What happens if the condition in a do-while loop is always true?
The loop runs indefinitely — an infinite loop. Unlike an infinite while (true) which developers write intentionally, an always-true condition in do-while is usually a bug where the condition variable is not updated inside the body. In production, this causes the thread executing the loop to hang, blocking any work that thread was supposed to do. The fix is to ensure the condition variable is modified inside the body, or to add a break on a specific exit condition.
Q6. Can you use break inside a do-while loop in Java?
Yes. A break inside a do-while body immediately exits the loop, bypassing the condition check entirely. This is useful when the exit condition is complex and more naturally expressed inside the body than in the while clause. In a menu loop, for example, break might be used to exit on certain error states while the while clause handles normal exit by choice number.
FAQs
What is the do-while loop used for in Java?
The do-while loop is used when the loop body must run at least once before the exit condition is checked. Common use cases are menu-driven programs, input validation, game loops where one round must always happen, and any scenario where the condition depends on something performed inside the body.
Why does do-while always execute at least once?
Because the condition is placed at the end of the loop, after the body. The body runs unconditionally on the first pass. The condition is evaluated after the body completes, and only then determines whether to run the body again. This is the fundamental structural difference from while and for.
What is the semicolon after do-while in Java?
The semicolon after } while (condition); is a required part of the do-while syntax. It terminates the statement. Forgetting it causes a compile-time error. This semicolon does not exist in while or for loops — it is unique to do-while.
How do I prevent an infinite loop in do-while?
Ensure the condition variable is updated inside the body so the condition eventually becomes false, or add a break statement that triggers when a maximum count or exit condition is reached. A do-while with a condition that can never become false will run indefinitely.
When should I use while instead of do-while?
Use while when the body might legitimately need to run zero times — when the starting state could already satisfy the exit condition and no initial execution is required. If you are iterating over a list that might be empty, or polling a resource that might already be in the desired state, while is safer because it checks the condition first.
Is do-while commonly used in production Java code?
Less commonly than while and for, but it appears regularly in specific patterns: interactive menu systems, input validation loops, retry mechanisms where at least one attempt must always be made, and game loops. When the genuine use case for do-while appears, it produces cleaner code than forcing while to do the same job.
Summary
The do-while loop has one defining purpose: guarantee the loop body runs at least once. The condition check comes after the body — that single structural difference is what makes it correct for input validation, menu systems, and initialization patterns where the first execution must always happen.
Two practical rules distinguish well-written do-while usage from misuse: first, if the body might need to run zero times, use while instead; second, never forget the semicolon after the while clause — it is the only Java loop construct that requires one.
For interviews, know the behavioral difference between do-while and while by name and be ready to give a concrete example where do-while is the cleaner choice — input validation is the clearest one. The distinction between post-test and pre-test loops comes up regularly at both service-based definition questions and product-based design discussions.
What to Read Next
| Topic | Link |
|---|---|
| How the while loop handles iteration when the body might not need to run | while Loop → |
| How the for loop handles iteration with a known count and explicit counter | for Loop → |
| How the switch statement handles discrete value matching inside loop menus | switch Statement → |