Beginner 4 min · March 05, 2026

Java While/Do-While — Forgotten Increment Breaks Everything

In Java, do-while runs at least once; while may skip.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
Plain-English First

Imagine you're washing dishes. You keep washing as long as there are dirty dishes in the sink — that's a while loop. You check the sink first, and if it's already empty, you never even pick up the sponge. A do-while loop is like a vending machine: it always dispenses something first, THEN asks if you want more. You always go through the action at least once, no matter what. That's the entire difference between these two loops.

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.

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.

RocketCountdown.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.");
    }
}
Output
T-minus 5 seconds...
T-minus 4 seconds...
T-minus 3 seconds...
T-minus 2 seconds...
T-minus 1 seconds...
Liftoff! The loop ran 5 times total.
Key Insight:
Notice that secondsRemaining-- inside the loop is what makes the condition eventually become false. Every while loop needs something inside it that moves the condition closer to false. Always ask yourself: 'What inside this loop will eventually make the condition fail?'

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);

PasswordChecker.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
    }
}
Output
Enter the password: hello
Wrong password. Try again.
Enter the password: password123
Wrong password. Try again.
Enter the password: OpenSesame
Access granted! It took you 3 attempt(s).
Watch Out:
The semicolon at the end of } while (condition); is mandatory in do-while loops. Forgetting it causes a compile error. This is one of the most common syntax mistakes beginners make — it feels unnatural because no other loop structure in Java ends with a semicolon.

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.

LoopComparison.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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.");
    }
}
Output
--- while loop with false condition ---
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.
Interview Gold:
This exact scenario — a condition that's false from the start — is the go-to interview question for distinguishing while from do-while. Be ready to say: 'A while loop runs zero times if the condition is initially false. A do-while always runs at least once.' Then give the cart/basket example above.

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.

CafeteriaMenu.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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();
    }
}
Output
=== Cafeteria Menu ===
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!
Pro Tip:
while (true) with a break is not bad practice — it's a widely used pattern in professional Java code for event loops, daemon threads, and interactive CLIs. What IS bad practice is an accidental infinite loop where you simply forgot to update the loop variable. The difference is intent and a clear, guaranteed break condition.
Feature / Aspectwhile Loopdo-while Loop
Condition check timingBEFORE the body executesAFTER the body executes
Minimum executionsZero — can be skipped entirelyOne — always runs at least once
Semicolon required after?No — ends with closing brace }Yes — } while (condition);
Best use caseWhen you might not need to run at allWhen you always need one run first (e.g., input)
Syntax opening keywordwhile (condition) {do {
Risk if condition starts falseBody is skipped completelyBody runs once regardless
Common real-world exampleProcessing items in a queuePrompting user for input/validation
Readability for 'run at least once'Needs workaround (duplicate code)Natural and clean fit

Key takeaways

1
A while loop checks its condition BEFORE each run
it can execute zero times if the condition starts out false.
2
A do-while loop checks its condition AFTER each run
it always executes at least once, guaranteed, no matter what the condition is.
3
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.
4
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.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

FAQ · 3 QUESTIONS

Frequently Asked Questions

01
What is the difference between while and do-while loop in Java?
02
Can a while loop run zero times in Java?
03
What causes an infinite loop and how do I stop it?
🔥

That's Control Flow. Mark it forged?

4 min read · try the examples if you haven't

Previous
for Loop in Java
4 / 9 · Control Flow
Next
break and continue in Java