Beginner 7 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 & Principal Engineer

20+ years shipping production Java in banking & fintech. Lessons pulled from things that broke in production.

Follow
Verified
production tested
May 24, 2026
last updated
1,554
articles · all by Naren
✦ Definition~90s read
What is while and do-while Loop in Java?

Java's while and do-while loops are the language's most primitive iteration constructs — they repeat a block of code as long as a boolean condition remains true. The while loop evaluates the condition before each iteration, meaning it can execute zero times if the condition is false from the start.

Imagine you're washing dishes.

The do-while variant flips this: it executes the body once unconditionally, then checks the condition after each pass, guaranteeing at least one execution. These loops exist because not all iteration problems fit the fixed-step pattern of for loops — you use them when you don't know the number of iterations ahead of time, like reading from a stream until EOF, polling a resource until available, or processing user input until a sentinel value.

They're the workhorses of state-driven loops, but their simplicity is a double-edged sword: a forgotten increment in the loop body doesn't cause a compile error — it silently creates an infinite loop, corrupting program state by spinning forever on the same data. This is the classic trap that catches even experienced devs, especially when the increment is buried in complex logic or conditional branches.

Alternatives include for loops when you have a clear counter or iterable, and recursion for functional-style iteration, but while/do-while remain essential for scenarios where the loop's continuation depends on mutable state that changes inside the body — just don't forget to update that state.

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.

The While/Do-While Trap: How a Forgotten Increment Corrupts State

A while loop in Java repeatedly executes a block of code as long as a boolean condition evaluates to true. The condition is checked before each iteration — if it's false initially, the body never runs. The do-while variant guarantees at least one execution by checking the condition after the body. Both are control flow primitives for indefinite iteration, where the number of iterations isn't known at entry.

The critical property: the loop variable or condition must be mutated inside the body, or you get an infinite loop. In practice, the most common failure is forgetting to increment a counter or advance a cursor. The JVM doesn't enforce this — it's purely a logic error. The condition is re-evaluated each pass, so any side effect that eventually flips it to false is required. A do-while is identical except the first iteration is unconditional.

Use while when you need to skip the body entirely if the condition is false upfront — e.g., reading from a stream that might be empty. Use do-while when the body must run at least once, like retry logic or menu prompts. In production systems, while loops often appear in polling loops, batch processors, and I/O read loops. The choice between them is about the first-iteration guarantee, not performance.

Infinite Loop Risk
Forgetting to increment the loop counter is the #1 cause of runaway while loops in production — the condition never flips, and the thread hangs forever.
Production Insight
A batch job polling a database with while(hasMoreRows) forgot to call rs.next() inside the loop — the result set never advanced, causing an infinite loop that saturated the connection pool and took down the service.
Symptom: thread dump shows a single thread stuck in a while loop with no I/O wait, CPU pinned at 100% on that core.
Rule of thumb: always verify that every path through a while body mutates the condition variable — use a counter guard or timeout as a safety net.
Key Takeaway
A while loop checks the condition before each iteration; a do-while checks after, guaranteeing at least one execution.
The loop variable must be mutated inside the body — forgetting an increment is the most common production bug.
Use do-while only when the body must execute unconditionally once; otherwise prefer while for clarity.
Java While/Do-While Loop Pitfalls THECODEFORGE.IO Java While/Do-While Loop Pitfalls Flow from condition-check to action, with trap of forgotten increment while Loop: Condition First Evaluates boolean before each iteration do-while Loop: Action First Executes body then checks condition Forgotten Increment Variable never updated leads to infinite loop Infinite Loop & break Use break to exit; continue skips rest Logic Bug Masking Loop runs but condition never met Production Condition Fail Edge cases break assumed invariants ⚠ Forgotten increment causes infinite loop Always update loop variable inside body or condition THECODEFORGE.IO
thecodeforge.io
Java While/Do-While Loop Pitfalls
While Do While Java

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.

The Hidden Cost: When while Loops Mask Logic Bugs

Most devs think they understand while loops. But when a condition is complex—say, combining multiple boolean checks or reading from a stream—the real danger isn't the loop itself. It's the state mutation you forget. I've seen a scheduled job silently fail because a while (fileReader.ready()) loop consumed a stream but never advanced the pointer. The result? 20,000 poll attempts per minute on an empty buffer. Why does this happen? Because while forces you to manage state inside the body. Every iteration depends on your last action. Miss an increment, skip a read, forget a flag toggle—and the loop becomes a CPU furnace. The fix: always test your loop invariant. Use a local variable as a sentinel, not a shared field. And when the logic feels tangled, rewrite as a for loop. The for loop's structure—initialization, condition, update—makes state transitions explicit. While is powerful, but it demands discipline.

FileProcessor.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// io.thecodeforge
import java.io.*;

public class FileProcessor {
    public void consumeLines(BufferedReader reader) throws IOException {
        String line;
        // BAD: No progression check
        while (reader.ready()) { 
            System.out.println("Still ready...");
            // Forgot: line = reader.readLine();
        }
    }
}
Output
Infinite loop: prints 'Still ready...' until heap overflow
Production Trap:
A missing reader.nextLine() or iterator.next() inside a while loop will freeze your thread. Always test with a timeout watchdog.
Key Takeaway
A while loop without state progression is a ticking bomb. Always ensure your condition eventually becomes false.

Flowcharts Lie: Why Code Conditions Fail in Production

Competitors love flowcharts: diamond boxes, arrows, clean logic. They show a nice loop where a condition check leads neatly to a body or exit. In production, that flowchart is a fairy tale. Why? Because conditions are rarely simple booleans. They involve null checks, timeout flags, thread interrupts, or external service calls. I debugged a payment retry loop that worked perfectly in QA. The flowchart said: 'while retries < 3 && payment.pending'. In production, the payment object became null mid-loop due to a race condition. The while condition threw a NullPointerException—silently swallowed by a generic catch block. The loop never terminated. Flowcharts can't capture transient states. They assume your data is immutable. My rule: treat every while condition as a list of failure points. Each expression should be null-safe, bounded, and testable. Use Optional or guard clauses before the loop, not inside it.

PaymentRetry.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// io.thecodeforge
import java.util.Optional;

public class PaymentRetry {
    public void process(Optional<Payment> paymentOpt) {
        int retries = 0;
        // Safe: fails fast if payment absent
        while (retries < 3 && paymentOpt.map(Payment::isPending).orElse(false)) {
            retries++;
            System.out.println("Retry " + retries);
        }
    }
}
Output
Exits cleanly if payment is null: never enters the loop.
Incident Pattern:
A condition that throws exception inside while triggers an infinite loop. Always wrap condition in a try-catch that sets condition to false.
Key Takeaway
Treat loop conditions as contracts: each term must be safe to evaluate. If one breaks, the contract fails.
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?
N
Naren Founder & Principal Engineer

20+ years shipping production Java in banking & fintech. Lessons pulled from things that broke in production.

Follow
Verified
production tested
May 24, 2026
last updated
1,554
articles · all by Naren
🔥

That's Control Flow. Mark it forged?

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

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