Java do-while Loop
Table of Contents + −
In the last lesson you learned about the Java while loop. A while checks the condition first, so a false start means the body never runs.
But sometimes you want the body to run at least once, like showing a menu before asking whether to quit. For that, Java gives you the do-while loop.
🤔 Why run first, then check?
Picture a coffee machine. It shows the drink menu first, then asks “anything else?” It does not check whether you want a drink before showing the menu. You need to see the menu at least once to decide.
That is what the do-while loop was made for:
- The body runs first, before any checking.
- Then the condition is checked at the bottom.
- True means loop back and run the body again.
- False means the loop stops.
So the body always runs at least once. A plain while cannot promise that. That single guarantee is the whole reason this loop exists.
🧩 The do-while syntax
The shape flips the usual order. Here is the bare shape of a do-while loop.
do { // this runs first, at least once} while (condition);- The body comes first, right after
do. - The condition sits at the bottom, after
while. - True jumps back to the top; false ends the loop.
- A semicolon is required after
while (condition). No other loop needs one there, so it is easy to forget.
Let’s count to 5 with a do-while so you can see it move. This prints the numbers 1 through 5.
int i = 1;do { System.out.println(i); // ✅ prints the current value i++; // ✅ then move forward} while (i <= 5);Here is what happens step by step:
- Java prints
i(1), theni++makes it 2. - It checks
i <= 5. True, so it loops back. - This keeps going while
iis 5 or less. - When
ibecomes 6,i <= 5is false and the loop stops.
The output matches what a while would give, because the condition was already true at the start. The difference shows up only in one special case, next.
Output
12345🔍 The key difference from while
The real difference shows up when the condition is false from the start.
- A
whilechecks first, so it runs zero times. - A
do-whilechecks after, so it runs once anyway.
Let’s prove it with two loops side by side using the same starting values.
First the while version. i starts at 10 and the condition asks for i < 5, already false. So this body never runs.
int i = 10;while (i < 5) { System.out.println("while: " + i); // ❌ never reached}System.out.println("while finished");The condition is false right away, so Java skips the body and jumps to the line after the loop. You only see the “finished” line.
Output
while finishedNow the do-while version, same numbers. This time the body runs once before the check, so you get one extra line.
int i = 10;do { System.out.println("do-while: " + i); // ✅ runs once before any check} while (i < 5);System.out.println("do-while finished");The body runs first and prints do-while: 10. Then Java checks i < 5, finds it false, and stops.
That single line, which the while never produced, is the entire personality of the do-while loop.
Output
do-while: 10do-while finishedKeep this picture in your head. A while is “check, then maybe act.” A do-while is “act, then check whether to act again.” Same family, opposite order.
🍽️ A real menu example
A menu is the classic home of do-while. It must show at least once, then repeat until the user picks the exit option. Here is a menu with three choices.
import java.util.Scanner;
public class Menu { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice;
do { System.out.println("1. Play"); System.out.println("2. Settings"); System.out.println("3. Exit"); System.out.print("Choose an option: "); choice = scanner.nextInt(); } while (choice != 3); // ✅ semicolon required here
System.out.println("Goodbye!"); }}Let’s read what this does:
- The menu prints first, every time the body runs.
- Then it reads the user’s choice into
choice. choice != 3is true for anything other than 3, so the loop repeats and shows the menu again.- Type 3 and the condition becomes false, so the loop ends.
The menu is guaranteed to appear at least once. Even picking 3 immediately still shows the menu first.
Here is a sample run where the user picks 1, sees the menu again, then picks 3 to leave.
Output
1. Play2. Settings3. ExitChoose an option: 11. Play2. Settings3. ExitChoose an option: 3Goodbye!A second natural use is input validation: asking the user for input and refusing to move on until the input is valid. You must ask at least once, so do-while fits perfectly. This loop keeps asking for an age until the user types a positive number.
import java.util.Scanner;
public class AgeCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int age;
do { System.out.print("Enter your age (a positive number): "); age = scanner.nextInt(); } while (age <= 0); // ✅ ask again while the input is invalid
System.out.println("Thank you. Your age is " + age); }}The program asks once no matter what, then checks the input. Zero or negative makes age <= 0 true, so it asks again. A sensible number ends the loop.
Here is a run where Riya types a wrong value first, then a correct one.
Output
Enter your age (a positive number): -4Enter your age (a positive number): 27Thank you. Your age is 27📊 for vs while vs do-while
All three repeat code, but each shines in a different situation. This table lines them up so you can pick quickly.
| Loop | When the condition is checked | Can run zero times? | Best for |
|---|---|---|---|
for | Before the body | Yes | A known number of repeats, like counting from 1 to 10 |
while | Before the body | Yes | Repeat while something is true, count unknown |
do-while | After the body | No, runs at least once | Menus and input that must run at least once |
The quick way to choose:
for: you know how many times to repeat.while: count unknown, and zero runs is fine.do-while: the body must run at least once.
That “at least once” promise is the only difference between while and do-while, but it matters a lot for menus and prompts.
⚠️ Common Mistakes
A few do-while slip-ups catch almost everyone, each with a wrong way and a right way.
Forgetting the closing semicolon is the most common. The while (condition) at the bottom needs a semicolon, or the code will not compile.
// ❌ Wrong: no semicolon after while (...)do { System.out.println("hi");} while (count < 3)
// ✅ Right: semicolon at the very enddo { System.out.println("hi");} while (count < 3);The next is reaching for do-while when a plain while fits better. If the body should be able to run zero times, a do-while runs once when it should not have.
// ❌ Wrong: prints "Item: ..." even when the list is emptyint i = 0;do { System.out.println("Item: " + items[i]); i++;} while (i < items.length);
// ✅ Right: a while runs zero times when the list is emptyint i = 0;while (i < items.length) { System.out.println("Item: " + items[i]); i++;}The last is the infinite loop: a loop that never stops because nothing in the body ever makes the condition false. The program keeps running and never reaches the code after it. Always change something in the body so the loop can end.
// ❌ Wrong: count never changes, so the loop runs foreverint count = 1;do { System.out.println(count);} while (count <= 5);
// ✅ Right: count goes up, so the condition will become falseint count = 1;do { System.out.println(count); count++;} while (count <= 5);✅ Best Practices
Habits that keep your do-while loops clean and bug-free:
- Use it only when the body must run once. Menus, prompts, and “ask then check” patterns. If zero runs is valid, pick a plain
while. - Always end with the semicolon. Close with
while (condition);out of habit. - Guarantee an exit. Change something in the body so the condition can become false.
- Keep the body short. If it grows large, move the work into a method and call it inside the loop.
- Name your exit clearly. Make the exit choice obvious, like option 3 here.
🧩 What You’ve Learned
Let’s recap the do-while.
- ✅ A do-while loop runs its body first, then checks the condition, so the body always runs at least once.
- ✅ The body comes after
do, and the condition is at the bottom withwhile (condition);. - ✅ The difference from
whileshows when the condition starts false:whileruns zero times,do-whileruns once. - ✅ It is perfect for menus and input validation, where you must ask at least once.
- ✅ Use
forfor a known count,whilefor zero-or-more, anddo-whilefor one-or-more. - ✅ Remember the closing semicolon, and still update something to avoid an infinite loop.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
How many times does a do-while loop run its body at minimum?
Why: A do-while checks the condition after the body, so the body always runs at least one time.
- 2
Where is the condition checked in a do-while loop?
Why: The condition sits at the bottom in while (condition);, so it is checked after the body runs.
- 3
If the condition is false from the start, what does a do-while do?
Why: Because the check is after the body, the body runs once before the false condition stops it.
- 4
What is special about the end of a do-while loop?
Why: A do-while ends with a semicolon after while (condition);, which other loops do not require.
🚀 What’s Next?
You know three loops now. There is one more, made specially for going through every item in a collection like an array. It is the enhanced for loop, also called the for-each loop. Let’s learn it next.