Topic 39 of 119 4. Control Flow in Java Interactive Tutorial

Java do...while: Running a Loop Before Checking Its Condition

11 mins read Last updated: 22 Aug 2026 21,700 views

Direct Answer & Core Concept

A do-while loop repeats a block of code and then checks its condition at the bottom, after the body has already run. That single difference changes everything about how you should think about it. The guarantee is simple and absolute: the body always executes at least once, no matter what the condition says. The condition is only consulted to decide whether to go around again. This makes a do-while loop an exit-controlled loop, also called a post-test or bottom-tested loop, and it is the exact opposite of a plain while loop, which tests first and may run zero times. That guarantee is what you are actually buying, so use it when you genuinely need one guaranteed pass. Showing a menu before accepting a choice is the classic case, because the user cannot choose until they have seen the menu. Validating input once before looping is the other common one. If you do not need a guaranteed first pass, a plain while loop is the better choice, because it avoids running the body by accident when there was nothing to do. One small thing that catches everyone the first time: a do-while loop ends with a semicolon, after the closing brace. It is the only loop in Java that does, and the compiler error points confusingly close to the brace rather than the semicolon.

Detailed Explanation & Mechanics

1) The Syntax and the One Rule That Makes It Different

Main.java
Run Online
do {
    // the body runs first, always
} while (condition);
// note the semicolon

Compare that with a plain while loop, which tests first.

Questionwhiledo...while
When is the condition tested?Before the bodyAfter the body
Can the body run zero times?YesNo, never
Also calledEntry-controlledExit-controlled
Ends withA closing braceA brace plus a semicolon
Typical useRetry, poll, read until doneMenu prompt, validate once


Two flow diagrams comparing a while loop which tests the condition first and may run zero times against a do while loop which always runs the body once before testing
A while loop may run zero times. A do-while always runs the body once before it ever tests.

2) Execution Order, Step by Step

  1. The body runs immediately. No condition has been checked yet, so this always happens.
  2. Now the condition is evaluated. This is the first time Java looks at it.
  3. If true, control jumps back to the body and steps 1 and 2 repeat.
  4. If false, the loop ends.

Step 1 is the whole point. By the time Java evaluates the condition for the first time, your code has already had its first pass, which is exactly what makes the loop useful for input and menus.

Main.java
Run Online
final int LIMIT = 3;
int count = 0;
do {
    System.out.println("Body ran, count is " + count);
    count++;
} while (count < LIMIT);

Run that and the body executes three times, ending with count at 3. The condition is tested four times in total, because the last test is the one that says stop.

3) The Zero-Iteration Case That Cannot Happen

Here is the clearest way to see the difference. Set the starting value so the condition is already false.

Main.java
Run Online
final int LIMIT = 5;
final int START_ALREADY_DONE = 10;
int count = START_ALREADY_DONE;
do {
    System.out.println("this DOES print");
    count++;
} while (count < LIMIT);
System.out.println("Finished, count is now " + count);

The while version of this exact program prints nothing at all, because the condition is false before the first test. The do-while version prints one line and increments the counter, then discovers the condition is false and stops. That is the guarantee, demonstrated rather than asserted.


Diagram showing a while loop skipping its body entirely when the condition starts false next to a do while loop that always executes the body once first
Same starting value, same false condition. The while loop runs zero times, the do-while runs once.

Watch out for this: because the body always runs, a do-while loop will process one item even when your collection is empty. If an empty collection should mean no work at all, use a plain while loop or a for-each loop instead.

4) The Semicolon, and Why It Exists

Main.java
Run Online
// CORRECT
do {
    count++;
} while (count < LIMIT);
// WRONG: missing semicolon
do {
    count++;
} while (count < LIMIT)

The second version does not compile, and the error message points at the closing brace or the start of the next line, which is nowhere near the actual problem. It frustrates almost every beginner exactly once.

The reason is grammar rather than logic. In Java, an if, a for and a while are complete once their closing brace is reached. A do-while is not, because the condition is a separate clause that follows the block, and the semicolon terminates that clause. It is the only loop in the language that needs one.

5) The Real Use Case, a Menu Prompt

This is the situation a do-while loop exists for. The user must see the menu before they can choose from it, so the first pass cannot be conditional.

Main.java
Run Online
final int MENU_CHOICE = 1;
final int QUIT_CHOICE = 0;
int choice = 0;
boolean running = true;
while (running) {
    do {
        System.out.println("1. Create a report");
        System.out.println("2. View a report");
        System.out.println("0. Quit");
        choice = readChoice();
        if (choice != MENU_CHOICE && choice != 2 && choice != QUIT_CHOICE) {
            System.out.println("That is not a valid option, try again");
        }
    } while (choice != MENU_CHOICE && choice != 2 && choice != QUIT_CHOICE);
    switch (choice) {
        case MENU_CHOICE: System.out.println("Creating the report");
        break;
        case 2: System.out.println("Viewing the report");
        break;
        default: running = false;
    }
}

Read the nesting. The inner do-while redraws the menu until the user enters something valid. The outer while keeps the whole program alive until they quit. The inner loop is a do-while rather than a while precisely because the menu has to appear at least once before the user has anything to respond to.

The second real use case is validating one value before looping over a collection. There, a single do-while is often clearer than nesting two loops.

Main.java
Run Online
final int MIN_VALUE = 1;
final int MAX_VALUE = 100;
int entered;
do {
    System.out.println("Enter a number between " + MIN_VALUE + " and " + MAX_VALUE);
    entered = readNumber();
    if (entered < MIN_VALUE || entered > MAX_VALUE) {
        System.out.println("Out of range, try again");
    }
} while (entered < MIN_VALUE || entered > MAX_VALUE);
System.out.println("Accepted " + entered);

6) Choosing Between while and do...while

SituationUseWhy
Show a menu, then accept inputdo-whileThe prompt must appear at least once.
Ask for one value and validate itdo-whileYou must ask before you can check the answer.
Retry an operation until it workswhileYou may not want to try even once.
Read lines until end of filewhileAn empty file should do nothing.
Process a collectionfor-eachAn empty collection means no work at all.
CountingforIt keeps the count, bound and step together.

The last three are the practical guard rails. A do-while loop is the right tool in only a narrow band of situations, and outside that band it tends to cause off-by-one style bugs because it always does one more thing than you expected.

7) The Termination Guarantee Still Applies

A do-while loop guarantees one pass, not that it will ever stop. The same rule applies: something inside the body must move the condition toward false, or the loop runs forever after that first pass.

Forgetting the update here is slightly nastier than in a while loop, because the program does produce output before hanging. You get one correct-looking line and then silence, which can send you hunting in the wrong place.


Infographic of six common do while loop mistakes each shown with the wrong and the corrected code
Six do-while mistakes. The missing semicolon is the one everyone hits first.

MistakeSymptomFix
Missing semicolon after the braceCompile error near the closing brace.Add ; after }, unlike every other loop.
No update inside the bodyOne line of output, then the program hangs.Add the line that moves the condition toward false.
Used when a zero-pass is correctProcesses one item too many.Use a plain while loop instead.
Looping over an empty collectionOne extra iteration on an empty list.Use a for-each loop, which handles it correctly.
Update placed after a continueInfinite loop from the second pass onward.Put the update at the top of the body.
Nesting a while inside a do-whileWorks, but the menu logic is hard to follow.Extract the inner loop into its own method.

8) A Complete Example

Here is a full program showing all the important behaviours together.

Main.java
Run Online
final int LIMIT = 3;
final int START_ALREADY_DONE = 10;
// step one: the basic do-while
int count = 0;
do {
    System.out.println("Pass " + count);
    count++;
} while (count < LIMIT);
// step two: the zero-iteration proof. The body runs even
// though the condition is false from the very first test.
int alreadyDone = START_ALREADY_DONE;
do {
    System.out.println("This still runs once, alreadyDone is " + alreadyDone);
    alreadyDone++;
} while (alreadyDone < LIMIT);

The second part is the one to internalise. If you delete the do and turn it into a plain while loop, that print statement disappears completely, because the condition is false before the first test. Same condition, same starting value, completely different behaviour.

For the wider picture across all four loops, see the looping overview page. For the two-way version of this comparison, see if...else for two-way decisions.

Frequently Asked Questions

What is an exit-controlled loop?


A loop that tests its condition after running the body, so the body always executes at least once. A do-while loop is the standard example. It is the opposite of an entry-controlled loop such as a for or while loop.

Why does do-while need a semicolon?


Because the condition is a separate clause that follows the block, and the semicolon terminates that clause. An if, for or while loop is complete at its closing brace, but a do-while is not, which makes it the only loop in Java that requires a trailing semicolon.

When should I use do-while instead of while?


When the body must happen at least once regardless, such as displaying a menu before reading a choice or asking for one value before validating it. If the work should be skipped entirely when there is nothing to do, use a plain while loop.

Can a do-while loop run forever?


Yes. The one-pass guarantee says nothing about stopping. As with any loop, something inside the body must move the condition toward false, otherwise the loop runs forever after that first pass.

What happens if I use do-while on an empty collection?


The body runs once even though there is nothing to process, because the guarantee applies regardless of the data. Use a for-each loop when an empty collection should mean no iterations at all.

Is do-while faster than while?


No, they compile to effectively the same code. Choose based on whether you genuinely need a guaranteed first pass, not on performance.

Can a do-while loop be infinite on purpose?


Yes. Using do { ... } while (true); is a legitimate pattern, useful for a loop that exits through break, a return or an exception rather than through its condition.

Why does my do-while run one extra time?


Because it is designed to. The condition is checked after the body, so the last pass is the one where the condition turns false. If you did not want that pass, you needed a while loop.

Runnable Code Example: Java do...while

Java 17+
Main.java
Run Online
// Demonstrates the Java do-while loop.
public class DoWhileDemo {
    // Stand-ins for real input so this needs no imports
    // and runs in any online compiler.
    static int readChoice() {
        return 1;
        // pretend the user typed 1
    } static int readNumber() {
        return 50;
        // pretend the user typed 50
    } public static void main(String[] args) {
        final int LIMIT = 3;
        final int START_ALREADY_DONE = 10;
        final int MIN_VALUE = 1;
        final int MAX_VALUE = 100;
        final int MENU_CHOICE = 1;
        final int QUIT_CHOICE = 0;
        // 1) THE BASIC do-while
        //    The body runs first, then the condition is checked.
        System.out.print("basic: ");
        int count = 0;
        do {
            System.out.print(count + " ");
            count++;
        } while (count < LIMIT);
        // note the semicolon
        System.out.println();
        // 2) THE ZERO-ITERATION PROOF
        //    The condition is false from the very first test, yet the
        //    body still runs exactly once. A plain while loop here
        //    would print nothing at all.
        int alreadyDone = START_ALREADY_DONE;
        do {
            System.out.println("guaranteed pass, alreadyDone was " + alreadyDone);
            alreadyDone++;
        } while (alreadyDone < LIMIT);
        // 3) THE SAME CODE AS A while LOOP, for contrast.
        //    Nothing prints, because the condition is tested first.
        int whileCounter = START_ALREADY_DONE;
        while (whileCounter < LIMIT) {
            System.out.println("this never prints");
            whileCounter++;
        } System.out.println("the while version printed nothing, as expected");
        // 4) INPUT VALIDATION, the classic use case.
        //    You must ask before you can check the answer, so the
        //    body has to run at least once.
        int entered;
        do {
            System.out.println("enter a number between " + MIN_VALUE + " and " + MAX_VALUE);
            entered = readNumber();
            if (entered < MIN_VALUE || entered > MAX_VALUE) {
                System.out.println("out of range, try again");
            }
        } while (entered < MIN_VALUE || entered > MAX_VALUE);
        System.out.println("accepted " + entered);
        // 5) A MENU REDRAWS UNTIL THE CHOICE IS VALID.
        //    The prompt has to appear before the user can answer.
        int choice = 0;
        do {
            System.out.println("1. Create a report");
            System.out.println("0. Quit");
            choice = readChoice();
            if (choice != MENU_CHOICE && choice != QUIT_CHOICE) {
                System.out.println("not a valid option, try again");
            }
        } while (choice != MENU_CHOICE && choice != QUIT_CHOICE);
        System.out.println("menu choice was " + choice);
        // 6) THE INFINITE FORM, escaped by break rather than by
        //    the condition. Note the semicolon after while (true).
        final int EXIT_AFTER = 2;
        int rounds = 0;
        do {
            rounds++;
            if (rounds >= EXIT_AFTER) {
                break;
            }
        } while (true);
        System.out.println("infinite form exited after " + rounds + " rounds");
    }
}/*
    ACTUAL OUTPUT:

        basic: 0 1 2
        guaranteed pass, alreadyDone was 10
        the while version printed nothing, as expected
        enter a number between 1 and 100
        accepted 50
1. Create a report
0. Quit
        menu choice was 1
        infinite form exited after 2 rounds

    THE FOUR THINGS TO REMEMBER
    1) The body ALWAYS runs at least once, because the condition is
       checked at the bottom rather than the top.
    2) That makes it exit-controlled, the opposite of a while loop,
       which may run zero times.
    3) It ends with a semicolon after the closing brace, the only
       loop in Java that does.
    4) One guaranteed pass is not the same as terminating. The body
       must still move the condition toward false or the loop hangs
       after that first pass.
*/

Common Java Technical Interview Questions & Answers

Interview Prep
Q1: What is an exit-controlled loop and how does it differ from an entry-controlled loop?\nA1: An exit-controlled loop tests its condition after running the body, so the body always executes at least once. A do-while loop is exit-controlled, while for and while loops are entry-controlled and may run zero times.\nQ2: Why does a do-while loop require a semicolon at the end?\nA2: Because the condition is a separate clause that follows the block, and the semicolon terminates that clause. An if, for or while loop is complete at its closing brace, which makes do-while the only loop in Java needing one.\nQ3: When is a do-while loop the better choice over a while loop?\nA3: When the body must run at least once regardless of the condition, such as displaying a menu before reading a choice or asking for a value before validating it. If there is a chance there is nothing to do and the body should be skipped, a while loop is correct.\nQ4: Can a do-while loop run forever?\nA4: Yes. The one-pass guarantee says nothing about stopping. As with any loop, something in the body must move the condition toward false, otherwise it runs forever after the first pass. The form do { } while (true) is a deliberate infinite loop exited by break.\nQ5: What happens if you use a do-while loop on an empty collection?\nA5: The body runs once even though there is nothing to process, because the guarantee applies regardless of the data. Use a for-each loop when an empty collection should mean zero iterations.\nQ6: Why does my do-while loop appear to run one extra time?\nA6: That is by design. The condition is checked after the body, so the final pass is the one where the condition becomes false. If you did not want that pass, the loop should have been a while loop.\nQ7: Is a do-while loop slower than a while loop?\nA7: No, they compile to effectively identical code. The choice is purely about whether you need a guaranteed first pass, not about performance.\nQ8: How do you exit a do-while loop early?\nA8: Use the break statement, exactly as in any other loop. With the deliberate do { } while (true) form, break is the only way out short of a return or an exception.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Use a do-while loop only when the body genuinely must execute once before the condition can be evaluated, such as a menu prompt or a single input validation, and use a plain while loop in every other case.\nAlways include the trailing semicolon after the closing brace, since it is the only loop in Java that requires it and forgetting it produces a confusing compile error near the wrong line.\nDo not use a do-while loop to iterate a collection, because the guaranteed first pass means an empty collection is still processed once, which is almost never what you want.\nPlace the state update at the top of the body, before any continue or break that could skip it, so the loop still terminates on later passes.\nPrefer a for-each loop for traversal and a for loop for counting, and reserve do-while for the narrow case of a mandatory first pass.\nKeep the condition readable by naming the values it tests, so the reason the loop repeats is obvious to the next reader.\nWhen using the deliberate do { } while (true) form, make sure a break, a return or an exception is always reachable, and document which one ends the loop.\nAvoid deeply nesting loops to build a menu, and extract the inner validation loop into its own method so each level does one job.\nRemember that the one-pass guarantee is about the first iteration only, and do not treat it as a substitute for a termination guarantee on later passes.\nWhen a loop runs one iteration too many, check whether a while loop was the correct construct before adding a condition to work around the do-while.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.