while and do-while Loops in Java Explained — With Real Examples
Every app you've ever used runs on repetition. Your phone's lock screen keeps checking your fingerprint until it matches. A game keeps looping frames at 60 times per second. A checkout system keeps scanning items until you're done. Without loops, you'd have to write the same line of code thousands of times — one for each repetition. Loops are what turn a 10,000-line nightmare into 10 elegant lines. They're not optional knowledge; they're the heartbeat of every real program you'll ever write.
The problem loops solve is simple: you don't always know in advance how many times you need to repeat something. For loops are great when you DO know (loop exactly 10 times). But when you're waiting for a user to type the right password, or processing data until you hit the end of a file, you need a loop that keeps running based on a condition — not a fixed count. That's exactly what while and do-while loops are built for.
By the end of this article, you'll understand exactly how while and do-while loops work in Java, when to choose one over the other, what an infinite loop is and how to avoid it, and the subtle but critical difference that trips up beginners in interviews. You'll also have four complete, runnable programs you can copy, run, and experiment with yourself.
How the while Loop Works — Condition First, Always
A while loop has one job: keep executing a block of code for as long as a condition remains true. Before every single iteration, Java evaluates the condition. If it's true, the block runs. If it's false, Java skips the block entirely and moves on. This means a while loop can execute zero times if the condition is false right from the start.
Think of a bouncer at a club. Before every person enters, the bouncer checks their ID. If you're under age the very first time you approach, you never get in — not even once. The 'check first' behavior is the defining trait of a while loop.
Here's the syntax stripped to its bones:
while (someCondition) { // code that runs while condition is true }
The condition must be a boolean expression — something that evaluates to either true or false. Inside the block, something must eventually change so the condition becomes false. If nothing changes, you get an infinite loop, and your program freezes. We'll cover that in the Gotchas section. Let's look at a real example first.
public class RocketCountdown { public static void main(String[] args) { int secondsRemaining = 5; // Start the countdown at 5 // Keep looping as long as we haven't hit zero while (secondsRemaining > 0) { System.out.println("T-minus " + secondsRemaining + " seconds..."); // CRITICAL: Decrease the counter each time, or this runs forever secondsRemaining--; // Same as: secondsRemaining = secondsRemaining - 1 } // This line only runs after the while loop's condition becomes false System.out.println("Liftoff! The loop ran " + (5 - secondsRemaining) + " times total."); } }
T-minus 4 seconds...
T-minus 3 seconds...
T-minus 2 seconds...
T-minus 1 seconds...
Liftoff! The loop ran 5 times total.
How the do-while Loop Works — Action First, Check Later
A do-while loop is the mirror image of a while loop. Instead of checking the condition before the first run, it runs the block first and checks the condition afterwards. This guarantees the code inside runs at least once, no matter what.
This might sound like a small difference, but it changes everything in the right scenario. The classic real-world case is a menu-driven program. You always want to show the menu at least once before asking the user to pick an option. With a while loop you'd have to display the menu both before the loop AND inside it. With a do-while, you show it once inside and let the loop handle the rest.
Another great example: input validation. You always need to ask the user for input at least once. You can't check if the input is valid before you've even asked for it. A do-while makes that natural.
The syntax uses the do keyword to open the block, and the while condition comes at the very end — note the semicolon after the closing parenthesis, which beginners often forget:
do { // code that always runs at least once } while (someCondition);
import java.util.Scanner; public class PasswordChecker { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); String correctPassword = "OpenSesame"; // The password we're checking against String enteredPassword; // Will hold what the user types int attemptCount = 0; // Track how many tries the user takes // do-while is perfect here: we ALWAYS need to ask at least once // We can't validate input we haven't collected yet do { System.out.print("Enter the password: "); enteredPassword = userInput.nextLine(); // Read what the user typed attemptCount++; // Count this attempt // Check if they got it wrong — give a hint if so if (!enteredPassword.equals(correctPassword)) { System.out.println("Wrong password. Try again."); } } while (!enteredPassword.equals(correctPassword)); // Keep looping if wrong // This line only runs once the correct password is entered System.out.println("Access granted! It took you " + attemptCount + " attempt(s)."); userInput.close(); // Good habit: always close your Scanner when done } }
Wrong password. Try again.
Enter the password: password123
Wrong password. Try again.
Enter the password: OpenSesame
Access granted! It took you 3 attempt(s).
while vs do-while — Choosing the Right Tool
Now that you've seen both loops in action, let's nail down exactly when to use each one. The decision comes down to a single question: does the loop body need to run before you can evaluate the condition?
If the answer is no — you can check the condition before doing anything — use a while loop. Countdown timers, processing a list of items, waiting for a flag to flip: these are while loop territory. The condition is independent of anything that happens inside the loop body.
If the answer is yes — you need to do something at least once before you can meaningfully check — use a do-while loop. User input validation, displaying a menu, rolling a dice at least once before asking to re-roll: these are do-while territory.
A useful mental test: 'Could it be correct to skip this loop entirely on the first pass?' If yes, use while. If no — it must always run at least once — use do-while.
The example below shows both loops handling the same scenario so you can see the structural difference side by side.
public class LoopComparison { public static void main(String[] args) { // ── SCENARIO A: Condition is FALSE from the start ── // while loop: the body is SKIPPED entirely (runs 0 times) int itemsInCart = 0; System.out.println("--- while loop with false condition ---"); while (itemsInCart > 0) { // This line never prints because itemsInCart is already 0 System.out.println("Processing item..."); } System.out.println("while loop finished. Ran 0 times."); System.out.println(); // ── SCENARIO B: Same condition, but with do-while ── // do-while: the body ALWAYS runs at least once int productsInBasket = 0; System.out.println("--- do-while loop with false condition ---"); do { // This line DOES print once, even though the condition is false System.out.println("Processing product... (ran at least once!)"); } while (productsInBasket > 0); // Condition checked AFTER the first run System.out.println("do-while loop finished. Ran 1 time."); } }
while loop finished. Ran 0 times.
--- do-while loop with false condition ---
Processing product... (ran at least once!)
do-while loop finished. Ran 1 time.
Infinite Loops, break, and continue — Taking Control
An infinite loop is a loop whose condition never becomes false, so it runs forever — or until your computer runs out of patience. Sometimes that's a bug (you forgot to update the counter). But sometimes it's intentional: game loops, server listeners, and real-time dashboards are all deliberately infinite loops that rely on break to exit when needed.
The break keyword immediately exits the loop entirely, no matter what the condition says. The continue keyword skips the rest of the current iteration and jumps back to the condition check. Think of break as an emergency exit door, and continue as skipping to the next item without leaving the building.
Using an intentional while (true) loop with a break inside is a legitimate and common pattern — especially for menus and server loops. It can actually be cleaner than cramming all the exit logic into the condition itself. Just make sure your break condition is airtight, or you'll be back to an accidental infinite loop.
import java.util.Scanner; public class CafeteriaMenu { public static void main(String[] args) { Scanner customerInput = new Scanner(System.in); double totalBill = 0.0; // Intentional infinite loop — this is a deliberate design choice // The loop keeps showing the menu until the customer chooses to leave while (true) { // Display menu options every time the loop runs System.out.println("\n=== Cafeteria Menu ==="); System.out.println("1. Coffee - $2.50"); System.out.println("2. Sandwich - $5.00"); System.out.println("3. Cake - $3.75"); System.out.println("4. Checkout (exit)"); System.out.print("Your choice: "); int menuChoice = customerInput.nextInt(); if (menuChoice == 1) { totalBill += 2.50; System.out.println("Coffee added to your order."); } else if (menuChoice == 2) { totalBill += 5.00; System.out.println("Sandwich added to your order."); } else if (menuChoice == 3) { totalBill += 3.75; System.out.println("Cake added to your order."); } else if (menuChoice == 4) { // break exits the while(true) loop immediately System.out.println("\nThank you! Your total is: $" + totalBill); break; } else { // continue skips back to the top of the loop without doing anything else System.out.println("Invalid choice. Please try again."); continue; } } System.out.println("Have a great day!"); customerInput.close(); } }
1. Coffee - $2.50
2. Sandwich - $5.00
3. Cake - $3.75
4. Checkout (exit)
Your choice: 1
Coffee added to your order.
=== Cafeteria Menu ===
1. Coffee - $2.50
2. Sandwich - $5.00
3. Cake - $3.75
4. Checkout (exit)
Your choice: 2
Sandwich added to your order.
=== Cafeteria Menu ===
1. Coffee - $2.50
2. Sandwich - $5.00
3. Cake - $3.75
4. Checkout (exit)
Your choice: 4
Thank you! Your total is: $7.5
Have a great day!
| Feature / Aspect | while Loop | do-while Loop |
|---|---|---|
| Condition check timing | BEFORE the body executes | AFTER the body executes |
| Minimum executions | Zero — can be skipped entirely | One — always runs at least once |
| Semicolon required after? | No — ends with closing brace `}` | Yes — `} while (condition);` |
| Best use case | When you might not need to run at all | When you always need one run first (e.g., input) |
| Syntax opening keyword | `while (condition) {` | `do {` |
| Risk if condition starts false | Body is skipped completely | Body runs once regardless |
| Common real-world example | Processing items in a queue | Prompting user for input/validation |
| Readability for 'run at least once' | Needs workaround (duplicate code) | Natural and clean fit |
🎯 Key Takeaways
- A while loop checks its condition BEFORE each run — it can execute zero times if the condition starts out false.
- A do-while loop checks its condition AFTER each run — it always executes at least once, guaranteed, no matter what the condition is.
- Every loop must have something inside it that eventually makes the condition false — if nothing changes, you have an infinite loop and your program freezes.
- The do-while loop requires a semicolon after the closing
while (condition)— it's the only loop syntax in Java that ends with a semicolon, and forgetting it causes a compile error.
⚠ Common Mistakes to Avoid
- ✕Mistake 1: Forgetting to update the loop variable (creating an accidental infinite loop) — Symptom: your program freezes, the console hangs, CPU spikes to 100%, and you have to force-kill it. Fix: always identify what variable controls your condition and make sure something inside the loop changes it (e.g.,
counter++,itemsLeft--). Ask yourself before running: 'What line of code will eventually make this condition false?' - ✕Mistake 2: Missing the semicolon at the end of a do-while — Symptom: Java throws a compile error:
error: ';' expectedpointing to the line after your closing brace. Fix: Remember that do-while is the only loop in Java that ends with a semicolon —} while (condition);. A good memory trick: thedoneeds thewhileto close its sentence, and sentences end with punctuation. - ✕Mistake 3: Using
.equals()vs==to compare Strings inside a loop condition — Symptom: the loop never exits even when the user types the correct value, because==compares memory addresses, not content, soenteredPassword == correctPasswordis almost always false for String objects. Fix: always use.equals()for String comparison:enteredPassword.equals(correctPassword). This is an especially painful bug in do-while input validation loops.
Interview Questions on This Topic
- QWhat is the key difference between a while loop and a do-while loop in Java? Can you give a concrete example of when you'd choose do-while over while?
- QWhat happens if the condition in a while loop is false before the loop starts? What about in a do-while loop? Walk me through both cases with code.
- QIf I show you this code — `while (true) { ... }` — is that always a bug? How would you determine if it's intentional or a mistake, and how does `break` change the behavior?
Frequently Asked Questions
What is the difference between while and do-while loop in Java?
The core difference is when the condition is checked. A while loop checks the condition before executing the body — so it can run zero times. A do-while loop executes the body first and checks the condition afterwards — so it always runs at least once. Use do-while when you need the loop body to execute before you can meaningfully evaluate the exit condition, like asking a user for input.
Can a while loop run zero times in Java?
Yes, absolutely. If the condition in a while loop evaluates to false before the first iteration, the loop body is skipped entirely and Java moves on to the next statement. This is one of the most important behavioral differences between while and do-while. To see it in action, try while (false) { System.out.println("Never runs"); } — nothing prints.
What causes an infinite loop and how do I stop it?
An infinite loop happens when the loop's condition never becomes false, usually because the variable controlling the condition never gets updated inside the loop body. To fix it, identify the variable in your condition and make sure something inside the loop changes it with each iteration. In an emergency during testing, press Ctrl+C in the terminal to force-stop your program. Intentional infinite loops using while (true) are valid but must include a break statement to exit.
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.