do-while Loop in Java – Syntax and Examples
The do-while loop is a variation of the while loop that checks its condition after running the body. That small change guarantees the body runs at least once, which is exactly what you need for menus, "try again" prompts and other tasks that must happen before you can decide whether to repeat them.
This tutorial explains the syntax and flow of do-while, shows where it shines with runnable examples, and compares it with while and for.
1. Syntax and Flow
do {
// body: always runs at least once
} while (condition); // note the semicolon
- Run the body.
- Evaluate the condition.
- If it is
true, go back to step 1; otherwise continue after the loop.
Because the test comes at the end, do-while is called an exit-controlled loop. The semicolon after while (condition) is required.
2. Basic Example: At Least Once
public class DoWhileBasics {
public static void main(String[] args) {
int i = 1;
do {
System.out.print(i + " ");
i++;
} while (i <= 5);
System.out.println();
// The body runs once even though the condition is false from the start
int stock = 0;
do {
System.out.println("Checking stock... found " + stock);
} while (stock > 0);
// Same condition with while: the body never runs
while (stock > 0) {
System.out.println("never printed");
}
}
}
1 2 3 4 5 Checking stock... found 0
With stock = 0, the do-while body ran once, while the while loop with the same condition did not run at all.
3. Where "At Least Once" Matters
Counting the digits of a number is a neat example. Every number, including 0, has at least one digit, so the loop body must run at least once:
public class CountDigits {
// do-while handles 0 correctly: it has one digit
static int digits(int n) {
n = Math.abs(n);
int count = 0;
do {
count++;
n /= 10;
} while (n != 0);
return count;
}
public static void main(String[] args) {
for (int n : new int[] {0, 7, 450, -98765}) {
System.out.println(n + " has " + digits(n) + " digit(s)");
}
}
}
0 has 1 digit(s) 7 has 1 digit(s) 450 has 3 digit(s) -98765 has 5 digit(s)
A while (n != 0) loop would wrongly report 0 digits for the number 0.
4. Menu-Driven Programs
A menu must be shown before the user can choose to exit, which makes do-while the classic choice. The sample input is 1, 2, 9, 3:
import java.util.Scanner;
public class MenuLoop {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double balance = 1000;
int choice;
do {
System.out.println("1) Check balance 2) Deposit 500 3) Exit");
choice = in.nextInt();
switch (choice) {
case 1 -> System.out.println("Balance: " + balance);
case 2 -> { balance += 500; System.out.println("Deposited. New balance: " + balance); }
case 3 -> System.out.println("Goodbye!");
default -> System.out.println("Invalid option");
}
} while (choice != 3); // the menu is always shown at least once
}
}
1) Check balance 2) Deposit 500 3) Exit Balance: 1000.0 1) Check balance 2) Deposit 500 3) Exit Deposited. New balance: 1500.0 1) Check balance 2) Deposit 500 3) Exit Invalid option 1) Check balance 2) Deposit 500 3) Exit Goodbye!
5. Validating User Input
Ask first, then check, and repeat until the answer is valid. The sample input is 9, 0, 4:
import java.util.Scanner;
public class ValidateInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int rating;
do {
System.out.println("Rate us from 1 to 5:");
rating = in.nextInt();
if (rating < 1 || rating > 5) System.out.println(" " + rating + " is not valid, try again");
} while (rating < 1 || rating > 5);
System.out.println("Thanks for rating us " + rating + "!");
}
}
Rate us from 1 to 5: 9 is not valid, try again Rate us from 1 to 5: 0 is not valid, try again Rate us from 1 to 5: Thanks for rating us 4!
6. do-while vs while vs for
| Feature | do-while | while | for |
|---|---|---|---|
| Condition checked | After the body | Before the body | Before the body |
| Minimum number of runs | 1 | 0 | 0 |
| Semicolon after condition | Required | Must not be there | Not after the header |
| Typical use | Menus, prompts, retries | Unknown number of repeats | Counting, indexes |
7. Things to Know
- Variables declared inside the
doblock are not visible in thewhilecondition, because the block's scope ends at the closing brace. Declare them before the loop, aschoiceandratingare above. breakexits the loop;continuejumps straight to the condition check.- Like any loop, something must eventually make the condition false.
do-whileis used less often thanforandwhile, so use it only when "at least once" is really the intent.
8. Summary
do { ... } while (condition);runs the body first and checks the condition afterwards.- The body always runs at least once.
- It is ideal for menus, input validation and retry logic.
- Remember the trailing semicolon, and declare condition variables outside the block.
Related Tutorials
Reference: Oracle Java Tutorials: The while and do-while Statements