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
Frequently Asked Questions (FAQ)
Q1. What is a do-while loop in Java?
A loop that runs its body first and then checks a condition, repeating while the condition is true. Its body always runs at least once.
Q2. What is the main difference between while and do-while?
while checks the condition before the body and may run zero times. do-while checks after the body and runs at least once.
Q3. Why is there a semicolon after while in a do-while loop?
Because do { ... } while (condition); is one complete statement, and Java statements end with a semicolon. Forgetting it is a compile error.
Q4. When should I use a do-while loop?
When the body must run before the condition can be evaluated: showing a menu, asking for input and validating it, or attempting an operation and retrying on failure.
Q5. Is do-while an entry-controlled or exit-controlled loop?
Exit-controlled: the condition is tested at the end of each iteration. while and for are entry-controlled.
Q6. Can a do-while loop run zero times?
No. The body always runs at least once, even if the condition is false from the start.
Q7. Can I use break and continue in a do-while loop?
Yes. break exits the loop immediately. continue skips the rest of the body and goes to the condition check.
Q8. Why can't I use a variable declared inside the do block in the condition?
The block's scope ends at its closing brace, before while. Declare the variable before the do keyword and assign it inside the block.
Q9. How do I write an infinite do-while loop?
do { ... } while (true);. End it with break or return when needed.
Q10. Can a do-while loop be converted to a while loop?
Yes, by running the body once before the loop and then using while, or with while (true) and a break at the end. do-while expresses "at least once" more directly.
Q11. Is do-while commonly used?
Less than for and while. It is the right tool for a specific job, mainly menus, prompts and retry loops.
Q12. Can the do-while condition use multiple expressions?
Yes, combine them with logical operators: while (attempts < 3 && !success);.
Q13. Can do-while loops be nested?
Yes, and they can be mixed with other loop types. Keep nesting shallow for readability.
Q14. What happens if the condition never becomes false?
The loop runs forever. Make sure the body changes something the condition depends on, or provides a break.
Q15. How do I implement a retry with a limit using do-while?
int attempts = 0;
boolean ok;
do {
attempts++;
ok = tryConnect();
} while (!ok && attempts < 3);
Q16. Is do-while slower than while?
No. The difference is only in when the condition is checked; performance is the same.
Q17. Does Java have a repeat-until loop?
No, but do { ... } while (!condition); behaves like repeat-until: it repeats until the condition becomes true.
Q18. Can I use a do-while loop with a Scanner?
Yes. It is a common pattern for reading and validating input, as shown in the rating example: prompt, read, check, and repeat if the value is invalid.
Q19. Do I need braces in a do-while loop?
Braces are optional for a single statement, but they are almost always used because they make the structure clear.
Q20. Why does my do-while menu print the prompt twice?
Often because nextInt() leaves a newline in the input, and a following nextLine() reads that empty line. Call nextLine() once after nextInt(), or read whole lines and parse them.