Java do-while Loop
What is a do-while Loop?
A do-while loop is a close cousin of the while loop, with one important twist: it checks its condition AFTER running the loop body, not before. That means the body of a do-while loop always executes at least once, no matter what the condition evaluates to.
Basic Syntax
do {
// code to repeat
} while (condition);Key Difference From while
In a while loop, the condition is checked BEFORE the first iteration, so the body might never run. In a do-while loop, the body runs first, and the condition is only checked afterward, to decide whether to run it AGAIN.
while: body may never run
int count = 10;
while (count < 5) {
System.out.println("while: " + count);
count++;
}
System.out.println("while loop finished");while loop finished
do-while: body always runs once
int count = 10;
do {
System.out.println("do-while: " + count);
count++;
} while (count < 5);
System.out.println("do-while loop finished");do-while: 10 do-while loop finished
A Simple Counting Example
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Practical Use Case: A Menu Loop
do-while is the natural fit whenever you want to show something to the user AT LEAST ONCE before deciding whether to repeat — a text menu is the textbook example. You want the menu to display at least one time, then keep redisplaying until the user chooses to exit.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. View Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Balance: $500");
case 2 -> System.out.println("Deposit successful");
case 3 -> System.out.println("Withdrawal successful");
case 4 -> System.out.println("Goodbye!");
default -> System.out.println("Invalid option, try again.");
}
} while (choice != 4);while vs do-while
Aspect | while | do-while |
Condition checked | Before the body runs | After the body runs |
Minimum executions | 0 (may never run) | 1 (always runs at least once) |
Ends with semicolon | No | Yes — while (condition); |
Typical use | Sentinel loops, input validation | Menus, "run once then repeat" logic |
Practice Exercises
Write a do-while loop that asks the user to guess a number until they get it right.
Build a simple text-based menu using do-while with at least three options.
Use a do-while loop to print numbers 1 to 5, then modify it so the condition is initially false and observe that it still runs once.