ā˜• Java

Java Do While Loop — Syntax, Flow, Examples & Best Practices

Everything you need to know about Java Do While Loop — syntax, flow diagram, exit-controlled behavior, difference from while loop, input validation, menu programs, nested do-while, break, continue, anti-patterns, and real-world production code examples.

šŸ“…

Last Updated

March 2026

ā±ļø

Read Time

20 min

šŸŽÆ

Level

Beginner to Intermediate

šŸ·ļø

Chapter

8 of 35

What is a Do-While Loop in Java?

A do-while loop in Java is an exit-controlled loop — it executes its body first and then evaluates the boolean condition. This is the fundamental difference from the while loop, which checks the condition before executing the body. Because the condition is evaluated after the body, a do-while loop always executes its body at least once — regardless of whether the condition is initially true or false.

Java provides three loop types: for (known iteration count), while (condition checked before body — entry-controlled), and do-while (body executes first — exit-controlled). The do-while loop is the least commonly used of the three, but it is the most natural fit for specific real-world patterns — especially menu-driven programs, input validation, game loops, and retry logic — where the action must happen before you can decide whether to repeat.

A critical syntax rule: the do-while statement must end with a semicolon after the closing while(condition). Forgetting this semicolon is the most common compile-time mistake with do-while loops. Unlike while and for, the do-while loop is the only loop in Java that requires a semicolon to terminate the statement.

Do-While Loop — Syntax & Execution Flow

The do-while loop syntax is straightforward but has one critical difference from all other Java loops — the condition appears at the end, after the body. The body is wrapped in do { } and the condition follows in while(condition);. The semicolon at the end is non-optional.

šŸ“‹
Do-While Syntax

do { // body — executes FIRST, at least once // update variable here } while (condition); // ← semicolon REQUIRED Three essential components: (1) Body — the block of statements that execute first. (2) Condition — a boolean expression evaluated AFTER each body execution. (3) Update — inside the body, a statement that changes the loop variable toward making the condition eventually false. Forgetting the semicolon after while(condition) is a compile-time error — it is the single most common syntax mistake in do-while loops.

šŸ”„
Execution Flow — Step by Step

Step 1: Execute the loop body (runs unconditionally the first time). Step 2: Execute the update statement (inside body — e.g., i++). Step 3: Evaluate the condition. Step 4: If condition is TRUE — go back to Step 1 (repeat). Step 5: If condition is FALSE — exit the loop; continue with the next statement. Key insight: Step 1 always happens regardless of the condition. The condition only controls whether to REPEAT — not whether to START.

āš–ļø
Do-While vs While — The Critical Difference

while: checks condition → (if true) executes body → repeats. If condition is false initially, body NEVER runs. do-while: executes body → checks condition → (if true) repeats. Body ALWAYS runs at least once. Analogy: while is like 'check if it's raining before going outside.' do-while is like 'go outside first, then decide if you should come back in.' When the first action is mandatory regardless of the condition — use do-while.

ā˜• JavaDoWhileSyntax.java
public class DoWhileSyntax {
    public static void main(String[] args) {

        // āœ… Basic do-while loop — print 1 to 5
        int i = 1;                   // Initialization
        do {
            System.out.println("Count: " + i);  // Body executes first
            i++;                     // Update
        } while (i <= 5);            // Condition — semicolon required!
        // Output: Count: 1 through Count: 5

        System.out.println("After loop: i = " + i); // i = 6

        // āœ… KEY DEMO: condition FALSE from start — body still runs ONCE
        int j = 100;
        do {
            System.out.println("Body ran with j = " + j); // Prints ONCE
            j++;
        } while (j < 5);  // false immediately — but body already executed
        System.out.println("After loop: j = " + j); // j = 101

        // Compare: while loop — body NEVER runs when condition is false
        int k = 100;
        while (k < 5) {
            System.out.println("This NEVER prints"); // Never executes
            k++;
        }
        System.out.println("After while: k = " + k); // k = 100 — unchanged

        // āœ… Countdown with do-while
        int count = 5;
        do {
            System.out.println("Countdown: " + count);
            count--;
        } while (count > 0);
        System.out.println("Liftoff!");
        // Output: Countdown: 5, 4, 3, 2, 1, Liftoff!

        // āœ… Sum of numbers 1 to 10 using do-while
        int num = 1, sum = 0;
        do {
            sum += num;
            num++;
        } while (num <= 10);
        System.out.println("Sum 1 to 10 = " + sum); // 55
    }
}

Do-While Loop Examples — Common Patterns

These examples cover the most frequently used do-while loop patterns in Java — from number processing and digit operations to game-style loops and accumulator patterns. Each demonstrates why do-while is the natural choice over while in these scenarios.

ā˜• JavaDoWhileExamples.java
public class DoWhileExamples {
    public static void main(String[] args) {

        // āœ… Example 1: Sum of digits using do-while
        // do-while is natural here — number always has at least 1 digit
        int number = 74863;
        int digitSum = 0;
        int temp = number;
        do {
            digitSum += temp % 10;  // Extract last digit
            temp /= 10;             // Remove last digit
        } while (temp != 0);
        System.out.println("Sum of digits of " + number + " = " + digitSum); // 28

        // āœ… Example 2: Reverse a number
        int original = 9876;
        int reversed = 0;
        int n = original;
        do {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        } while (n != 0);
        System.out.println("Reverse of " + original + " = " + reversed); // 6789

        // āœ… Example 3: Count digits in a number
        int value = 500300;
        int digitCount = 0;
        int v = value;
        do {
            digitCount++;
            v /= 10;
        } while (v != 0);
        System.out.println("Digits in " + value + ": " + digitCount); // 6

        // āœ… Example 4: Factorial with do-while
        int factNum = 5;
        long factorial = 1;
        int f = factNum;
        do {
            factorial *= f;
            f--;
        } while (f > 1);
        System.out.println(factNum + "! = " + factorial); // 5! = 120

        // āœ… Example 5: Check palindrome number
        int num = 1331;
        int rev = 0, copy = num;
        do {
            rev = rev * 10 + copy % 10;
            copy /= 10;
        } while (copy != 0);
        System.out.println(num + " is palindrome: " + (num == rev)); // true

        // āœ… Example 6: Print multiplication table
        int table = 9;
        int multiplier = 1;
        System.out.println("--- Table of " + table + " ---");
        do {
            System.out.printf("%d x %2d = %2d%n", table, multiplier, table * multiplier);
            multiplier++;
        } while (multiplier <= 10);

        // āœ… Example 7: ATM-style PIN attempt (max 3 tries)
        int correctPin = 1234;
        int enteredPin = 0;
        int attempts = 0;
        int maxAttempts = 3;
        // Simulating PIN entries: 1111, 2222, 1234
        int[] simulatedInputs = {1111, 2222, 1234};
        do {
            enteredPin = simulatedInputs[attempts];
            attempts++;
            if (enteredPin == correctPin) {
                System.out.println("Access granted on attempt " + attempts);
                break;
            } else {
                System.out.println("Wrong PIN. Attempts left: " + (maxAttempts - attempts));
            }
        } while (attempts < maxAttempts);
        if (enteredPin != correctPin) {
            System.out.println("Card blocked after " + maxAttempts + " wrong attempts.");
        }
    }
}

Do-While vs While — Key Differences

The choice between do-while and while comes down to one question: must the body execute at least once? The table below covers every important dimension of the comparison.

Featuredo-while Loopwhile Loop
Loop typeExit-controlledEntry-controlled
Condition checkedAFTER body executesBEFORE body executes
Minimum executions1 — body always runs at least once0 — body may never run
Semicolon requiredYes — while(condition);No
Syntax positionCondition at the bottomCondition at the top
Best forMust execute body first; menu, validation, retryCondition may be false initially; file reading
If condition initially falseBody still runs onceBody never runs
Code duplication riskNone — body written onceMay need 'prime read' before loop (duplication)
ReadabilitySlightly more verboseSimpler for straightforward loops
Common use casesMenus, input validation, game rounds, retryFile reading, polling, condition-based loops
ā˜• JavaDoWhileVsWhile.java
import java.util.Scanner;

public class DoWhileVsWhile {
    public static void main(String[] args) {

        // āœ… SCENARIO: Read positive number from user

        // āŒ Using while — requires 'prime read' (code duplication)
        Scanner sc1 = new Scanner(System.in);
        System.out.print("[while] Enter a positive number: ");
        int num1 = sc1.nextInt();           // Prime read BEFORE loop
        while (num1 <= 0) {                 // Then check condition
            System.out.print("Invalid! Enter a positive number: ");
            num1 = sc1.nextInt();           // Read again inside loop
        }
        System.out.println("Valid input: " + num1);
        // Problem: reading logic duplicated in 2 places

        // āœ… Using do-while — cleaner, no duplication
        Scanner sc2 = new Scanner(System.in);
        int num2;
        do {
            System.out.print("[do-while] Enter a positive number: ");
            num2 = sc2.nextInt();           // Read once inside the loop
            if (num2 <= 0) {
                System.out.println("Invalid! Try again.");
            }
        } while (num2 <= 0);               // Repeat only if invalid
        System.out.println("Valid input: " + num2);
        // Advantage: reading logic in ONE place only

        // āœ… When condition is initially TRUE — both behave identically
        int a = 1;
        System.out.print("while: ");
        while (a <= 3) { System.out.print(a + " "); a++; }
        System.out.println();

        int b = 1;
        System.out.print("do-while: ");
        do { System.out.print(b + " "); b++; } while (b <= 3);
        System.out.println();
        // Both print: 1 2 3 — identical output when condition is true initially

        // āœ… When condition is initially FALSE — KEY difference
        int x = 10;
        System.out.print("while (x<5): ");
        while (x < 5) { System.out.print(x); x++; }
        System.out.println("(nothing printed)"); // Body never ran

        int y = 10;
        System.out.print("do-while (y<5): ");
        do { System.out.print(y + " "); y++; } while (y < 5);
        System.out.println();  // Prints: 10 — body ran once
    }
}

Input Validation with Do-While — The Classic Pattern

Input validation is the most common real-world use case for the do-while loop. The pattern is: read input first, then check if it is valid; if not valid, ask again. This is a perfect fit for do-while because you must read input at least once before you can evaluate it. Using a while loop for this requires duplicating the read statement — once before the loop and once inside.

āœ…
Why Do-While Is Perfect for Input Validation

Input validation has a natural 'execute first, then decide' structure: you cannot know if input is valid before reading it. A while loop forces you to prime the pump — read before the loop just to check the condition, then read again inside. This duplication is error-prone. A do-while reads exactly once per iteration, checks validity after, and repeats only when necessary. The logic is in one place, the code is DRY (Don't Repeat Yourself), and the flow matches the natural thought process.

šŸ”¢
What to Validate

Common validation scenarios for do-while: numeric range (age 1–120, percentage 0–100, quantity > 0), string format (non-blank name, valid email pattern, password strength), menu choice (valid option from a list), PIN/OTP (correct value within limited attempts), date input (valid day/month/year), and yes/no prompts (must be 'Y' or 'N'). In all these cases, the input must be read before it can be validated — making do-while the appropriate loop.

āš ļø
Handling Scanner with Do-While

When using Scanner for input validation, be careful with nextInt() and nextLine() mixing — nextInt() does not consume the newline, causing nextLine() to return empty on the next call. Fix: call sc.nextLine() after sc.nextInt() to consume the leftover newline. Also, wrap nextInt() in a try-catch for InputMismatchException when the user types non-numeric input, and call sc.nextLine() in the catch block to clear the invalid token from the scanner buffer before the next iteration.

ā˜• JavaInputValidation.java
import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // āœ… Validate age (must be 1 to 120)
        int age;
        do {
            System.out.print("Enter your age (1-120): ");
            age = sc.nextInt();
            if (age < 1 || age > 120) {
                System.out.println("āŒ Invalid age. Please try again.");
            }
        } while (age < 1 || age > 120);
        System.out.println("āœ… Valid age: " + age);

        // āœ… Validate percentage (0.0 to 100.0)
        double percentage;
        do {
            System.out.print("Enter percentage (0.0 - 100.0): ");
            percentage = sc.nextDouble();
            if (percentage < 0.0 || percentage > 100.0) {
                System.out.println("āŒ Percentage must be between 0 and 100.");
            }
        } while (percentage < 0.0 || percentage > 100.0);
        System.out.println("āœ… Valid percentage: " + percentage);

        sc.nextLine(); // Clear buffer after nextDouble()

        // āœ… Validate non-blank name
        String name;
        do {
            System.out.print("Enter your name (cannot be blank): ");
            name = sc.nextLine().strip();
            if (name.isBlank()) {
                System.out.println("āŒ Name cannot be blank.");
            }
        } while (name.isBlank());
        System.out.println("āœ… Hello, " + name + "!");

        // āœ… Validate yes/no input
        String answer;
        do {
            System.out.print("Continue? (Y/N): ");
            answer = sc.nextLine().strip().toUpperCase();
            if (!answer.equals("Y") && !answer.equals("N")) {
                System.out.println("āŒ Please enter Y or N only.");
            }
        } while (!answer.equals("Y") && !answer.equals("N"));
        System.out.println("āœ… You chose: " + answer);

        // āœ… Validate with exception handling (non-numeric input)
        int quantity = 0;
        boolean valid = false;
        do {
            System.out.print("Enter quantity (positive integer): ");
            try {
                quantity = sc.nextInt();
                if (quantity > 0) {
                    valid = true;
                } else {
                    System.out.println("āŒ Quantity must be positive.");
                }
            } catch (java.util.InputMismatchException e) {
                System.out.println("āŒ Please enter a valid integer.");
                sc.nextLine(); // Clear invalid token from buffer
            }
        } while (!valid);
        System.out.println("āœ… Quantity: " + quantity);

        sc.close();
    }
}

A menu-driven program is the textbook use case for the do-while loop. The menu must be displayed at least once before the user can make a choice. After processing the choice, the program asks if the user wants to continue. This repeat-until-exit pattern maps perfectly to do-while — the menu shows, the user acts, and the loop continues only if they choose to stay.

ā˜• JavaMenuProgram.java
import java.util.Scanner;

public class MenuProgram {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice;

        // āœ… Simple calculator menu with do-while
        do {
            // Show menu — runs at least once
            System.out.println("\n╔══════════════════════╗");
            System.out.println("ā•‘    CALCULATOR MENU   ā•‘");
            System.out.println("╠══════════════════════╣");
            System.out.println("ā•‘  1. Addition         ā•‘");
            System.out.println("ā•‘  2. Subtraction      ā•‘");
            System.out.println("ā•‘  3. Multiplication   ā•‘");
            System.out.println("ā•‘  4. Division         ā•‘");
            System.out.println("ā•‘  5. Exit             ā•‘");
            System.out.println("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•");
            System.out.print("Enter choice (1-5): ");
            choice = sc.nextInt();

            if (choice >= 1 && choice <= 4) {
                System.out.print("Enter first number: ");
                double a = sc.nextDouble();
                System.out.print("Enter second number: ");
                double b = sc.nextDouble();

                switch (choice) {
                    case 1 -> System.out.printf("Result: %.2f%n", a + b);
                    case 2 -> System.out.printf("Result: %.2f%n", a - b);
                    case 3 -> System.out.printf("Result: %.2f%n", a * b);
                    case 4 -> {
                        if (b == 0) System.out.println("āŒ Division by zero!");
                        else System.out.printf("Result: %.2f%n", a / b);
                    }
                }
            } else if (choice == 5) {
                System.out.println("Thank you for using the calculator. Goodbye!");
            } else {
                System.out.println("āŒ Invalid choice! Please enter 1-5.");
            }

        } while (choice != 5);  // Repeat until user chooses Exit

        sc.close();
    }
}
ā˜• JavaStudentMenuSystem.java — Multi-Level Menu
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class StudentMenuSystem {

    static List<String> students = new ArrayList<>();
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int choice;
        do {
            System.out.println("\n=== Student Management ===");
            System.out.println("1. Add Student");
            System.out.println("2. View All Students");
            System.out.println("3. Search Student");
            System.out.println("4. Remove Student");
            System.out.println("5. Exit");
            System.out.print("Your choice: ");
            choice = sc.nextInt();
            sc.nextLine(); // consume newline

            switch (choice) {
                case 1 -> addStudent();
                case 2 -> viewStudents();
                case 3 -> searchStudent();
                case 4 -> removeStudent();
                case 5 -> System.out.println("Exiting system...");
                default -> System.out.println("āŒ Invalid option!");
            }
        } while (choice != 5);
    }

    static void addStudent() {
        System.out.print("Enter student name: ");
        String name = sc.nextLine().strip();
        if (!name.isBlank()) {
            students.add(name);
            System.out.println("āœ… Added: " + name);
        } else {
            System.out.println("āŒ Name cannot be blank.");
        }
    }

    static void viewStudents() {
        if (students.isEmpty()) {
            System.out.println("No students found.");
            return;
        }
        System.out.println("\n--- Student List ---");
        int i = 1;
        for (String s : students) {
            System.out.println(i++ + ". " + s);
        }
    }

    static void searchStudent() {
        System.out.print("Enter name to search: ");
        String query = sc.nextLine().strip().toLowerCase();
        boolean found = false;
        for (String s : students) {
            if (s.toLowerCase().contains(query)) {
                System.out.println("āœ… Found: " + s);
                found = true;
            }
        }
        if (!found) System.out.println("āŒ No match found.");
    }

    static void removeStudent() {
        System.out.print("Enter name to remove: ");
        String name = sc.nextLine().strip();
        if (students.remove(name)) {
            System.out.println("āœ… Removed: " + name);
        } else {
            System.out.println("āŒ Student not found.");
        }
    }
}

Break and Continue in Do-While Loop

break and continue work inside do-while loops just as they do in while and for loops — but their interaction with the do-while's exit-controlled nature has subtle implications worth understanding. break exits the loop before the condition is even checked. continue skips the rest of the body and jumps directly to the condition check.

šŸ›‘
break in Do-While

break exits the do-while loop immediately, before the while condition is evaluated. This means the guaranteed 'at least once' execution can be cut short mid-body if break is hit on the first iteration. Use break in do-while for: early exit when a target is found, max attempt limits (e.g., 3 PIN attempts), error conditions that require immediate loop termination, and user cancellation mid-session. After break, execution resumes at the statement immediately after the closing while(condition);

ā­ļø
continue in Do-While

continue in a do-while loop skips the remaining statements in the current iteration body and jumps directly to the while(condition) check. If the condition is true, the body executes again from the top. If false, the loop exits. Critical difference from while loop: in a while loop, continue jumps to the condition at the top; in a do-while loop, continue jumps to the condition at the bottom — the update logic must still be before the continue or after (depending on design) to avoid unintended infinite loops.

šŸ’”
break vs continue in Do-While — Quick Guide

break: 'I'm done with the entire loop — exit now, skip condition check.' continue: 'I'm done with this iteration — check the condition and decide whether to run the body again.' In a do-while with a max-attempt PIN validation: use continue to skip printing when input is correct; use break to exit immediately upon success or when max attempts are exhausted. Always ensure the loop control variable is updated correctly before continue — otherwise the condition may never change and the loop runs forever.

ā˜• JavaBreakContinueDoWhile.java
public class BreakContinueDoWhile {
    public static void main(String[] args) {

        // āœ… break in do-while — exit on specific condition
        System.out.println("--- break in do-while ---");
        int i = 1;
        do {
            if (i == 4) {
                System.out.println("Breaking at i = " + i);
                break;  // Exits loop — while(i<=10) never checked for i=4
            }
            System.out.println("i = " + i);
            i++;
        } while (i <= 10);
        System.out.println("After loop: i = " + i); // i = 4
        // Output: i=1, i=2, i=3, Breaking at i=4

        // āœ… continue in do-while — skip specific iterations
        System.out.println("\n--- continue in do-while ---");
        int j = 0;
        do {
            j++;           // Update BEFORE continue to avoid infinite loop
            if (j % 2 == 0) {
                continue;  // Skip even numbers — jumps to while(j<=10)
            }
            System.out.print(j + " "); // Prints only odd: 1 3 5 7 9
        } while (j < 10);
        System.out.println();

        // āœ… Max attempts with break — ATM PIN pattern
        System.out.println("\n--- PIN Validation with break ---");
        int correctPin = 5678;
        int[] inputs = {1234, 0000, 5678}; // Simulated user inputs
        int attempt = 0;
        boolean unlocked = false;
        do {
            int entered = inputs[attempt];
            attempt++;
            System.out.println("Attempt " + attempt + ": Entered " + entered);
            if (entered == correctPin) {
                unlocked = true;
                System.out.println("āœ… Correct PIN! Access granted.");
                break;  // Exit on success
            }
            System.out.println("āŒ Wrong PIN. " + (3 - attempt) + " attempt(s) left.");
        } while (attempt < 3);
        if (!unlocked) System.out.println("šŸ”’ Card blocked.");

        // āœ… continue to skip null/invalid in do-while
        System.out.println("\n--- Skipping null values ---");
        String[] data = {"Alice", null, "Bob", "", "Charlie"};
        int k = 0;
        do {
            String item = data[k];
            k++;
            if (item == null || item.isBlank()) {
                continue;  // Skip null/blank, go to while(k < data.length)
            }
            System.out.println("Valid: " + item);
        } while (k < data.length);
        // Output: Valid: Alice, Valid: Bob, Valid: Charlie
    }
}

Nested Do-While Loops

Just like while and for loops, do-while loops can be nested — placing one do-while inside another. The inner loop executes completely for each iteration of the outer loop. Nested do-while loops are useful for 2D patterns, tabular data, and scenarios where both outer and inner iterations must execute at least once.

ā˜• JavaNestedDoWhile.java
public class NestedDoWhile {
    public static void main(String[] args) {

        // āœ… Example 1: Multiplication table grid
        int row = 1;
        do {
            int col = 1;
            do {
                System.out.printf("%4d", row * col);
                col++;
            } while (col <= 5);      // Inner: columns 1-5
            System.out.println();    // New line after each row
            row++;
        } while (row <= 5);           // Outer: rows 1-5
        //  1   2   3   4   5
        //  2   4   6   8  10
        //  3   6   9  12  15  ... etc

        // āœ… Example 2: Star pattern with nested do-while
        System.out.println();
        int r = 1;
        do {
            int s = 1;
            do {
                System.out.print("* ");
                s++;
            } while (s <= r);
            System.out.println();
            r++;
        } while (r <= 5);
        // *
        // * *
        // * * *
        // * * * *
        // * * * * *

        // āœ… Example 3: Number pyramid
        System.out.println();
        int line = 1;
        do {
            int num = 1;
            do {
                System.out.print(num + " ");
                num++;
            } while (num <= line);
            System.out.println();
            line++;
        } while (line <= 5);
        // 1
        // 1 2
        // 1 2 3
        // 1 2 3 4
        // 1 2 3 4 5

        // āœ… Example 4: Multi-level menu with nested do-while
        int outerChoice;
        do {
            System.out.println("\n--- MAIN MENU ---");
            System.out.println("1. Reports");
            System.out.println("2. Settings");
            System.out.println("3. Exit");
            System.out.print("Choice: ");
            outerChoice = new java.util.Scanner(System.in).nextInt();

            if (outerChoice == 1) {
                int reportChoice;
                do {
                    System.out.println("  --- REPORTS MENU ---");
                    System.out.println("  1. Daily Report");
                    System.out.println("  2. Monthly Report");
                    System.out.println("  3. Back to Main Menu");
                    System.out.print("  Choice: ");
                    reportChoice = new java.util.Scanner(System.in).nextInt();
                    if (reportChoice == 1) System.out.println("  Generating Daily Report...");
                    if (reportChoice == 2) System.out.println("  Generating Monthly Report...");
                } while (reportChoice != 3);  // Inner menu loop
            }
        } while (outerChoice != 3);  // Outer menu loop
        System.out.println("Goodbye!");
    }
}

Do-While vs For Loop — Comparison

While any loop type can technically replace any other, choosing the right one based on intent is a mark of experienced Java code. Here is how do-while compares against the for loop across all practical dimensions.

Aspectdo-while Loopfor Loop
Best forUnknown count; must execute at least onceKnown count; range or collection iteration
Condition locationBottom — evaluated after bodyTop — evaluated before body
Minimum executions1 — body always runs at least once0 — body may never run if condition false
InitializationBefore the loop (external)Inside loop header (self-contained)
Update placementInside body — flexibleThird part of for(;;) — always after each iteration
Semicolon requiredYes — while(condition);No (but semicolons separate the three parts)
ReadabilityBest for menu, validation, retry patternsBest for fixed range, index, collection traversal
Variable scopeControl variable accessible outside loopControl variable can be scoped inside for header
Code duplication riskNone — body written onceNone — but prime read needed for some patterns
Common use casesMenus, input validation, game rounds, retriesArray traversal, fixed iteration, index-based loops
ā˜• JavaDoWhileVsFor.java
public class DoWhileVsFor {
    public static void main(String[] args) {

        // āœ… For loop — best for known iteration count
        System.out.print("for loop: ");
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " "); // 1 2 3 4 5
        }
        System.out.println();

        // āœ… Equivalent do-while — more verbose for fixed range
        System.out.print("do-while equivalent: ");
        int i = 1;
        do {
            System.out.print(i + " "); // 1 2 3 4 5
            i++;
        } while (i <= 5);
        System.out.println();

        // āœ… Do-while — best for 'execute at least once' pattern
        // Game round — always play at least once, then ask to replay
        String playAgain;
        do {
            System.out.println("\nšŸŽ® Playing a game round...");
            // ... game logic here ...
            System.out.println("Round complete! Score: " + (int)(Math.random() * 100));
            System.out.print("Play again? (Y/N): ");
            playAgain = "N"; // Simulated input for demo
            System.out.println(playAgain);
        } while (playAgain.equalsIgnoreCase("Y"));
        System.out.println("Thanks for playing!");

        // āœ… For loop for same — needs extra flag logic (less clean)
        boolean firstRound = true;
        String continueGame = "Y";
        for (; firstRound || continueGame.equalsIgnoreCase("Y"); ) {
            firstRound = false;
            System.out.println("for-based game round");
            continueGame = "N"; // Simulated
        }
        // Less natural — do-while is clearly the better choice here
    }
}

Infinite Do-While Loop — do { } while(true)

Just like while(true), a do { } while(true) creates an intentional infinite loop that must be exited with break or return. The do-while variant is preferred when you want the body to always execute at least once before any exit condition is checked — common in server loops, game engines, and interactive shell applications.

ā˜• JavaInfiniteDoWhile.java
import java.util.Scanner;

public class InfiniteDoWhile {
    public static void main(String[] args) {

        // āœ… Pattern 1: Interactive shell / REPL loop
        Scanner sc = new Scanner(System.in);
        System.out.println("Simple Shell — type 'exit' to quit");
        do {
            System.out.print("> ");
            String command = sc.nextLine().strip().toLowerCase();
            switch (command) {
                case "hello" -> System.out.println("Hello, World!");
                case "date"  -> System.out.println("Today: " + java.time.LocalDate.now());
                case "help"  -> System.out.println("Commands: hello, date, help, exit");
                case "exit"  -> {
                    System.out.println("Goodbye!");
                    return;  // Exit entire program
                }
                default -> System.out.println("Unknown command: " + command);
            }
        } while (true);  // Loop forever until 'exit' triggers return

        // āœ… Pattern 2: Retry with exponential backoff (production pattern)
        // (Shown as structure — simulated service call)
        int attempt = 0;
        int maxAttempts = 5;
        do {
            attempt++;
            System.out.println("Service call attempt " + attempt);
            boolean success = attempt == 3; // Simulated: succeeds on 3rd try
            if (success) {
                System.out.println("āœ… Service call succeeded on attempt " + attempt);
                break;
            }
            if (attempt >= maxAttempts) {
                System.out.println("āŒ Max attempts reached. Giving up.");
                break;
            }
            long waitMs = 500L * (long) Math.pow(2, attempt - 1); // Backoff: 500ms, 1s, 2s...
            System.out.println("Retrying in " + waitMs + "ms...");
        } while (true);

        // āœ… Pattern 3: Event processing loop
        java.util.Queue<String> eventQueue = new java.util.LinkedList<>();
        eventQueue.add("LOGIN");
        eventQueue.add("PURCHASE");
        eventQueue.add("LOGOUT");
        eventQueue.add("SHUTDOWN");

        do {
            if (eventQueue.isEmpty()) {
                System.out.println("No events. Waiting...");
                break; // Exit if queue empty (in real code: wait/sleep)
            }
            String event = eventQueue.poll();
            System.out.println("Processing event: " + event);
            if ("SHUTDOWN".equals(event)) {
                System.out.println("Shutdown signal received. Stopping.");
                break;
            }
        } while (true);
    }
}

Common Mistakes & Pitfalls — Bugs That Fool Everyone

These are the most common do-while loop mistakes in Java — from missing semicolons and infinite loops caused by misplaced continues, to misunderstanding when the condition is actually evaluated.

ā˜• JavaDoWhileMistakes.java
// āŒ MISTAKE 1: Missing semicolon — compile error
int i = 1;
// do {
//     System.out.println(i);
//     i++;
// } while (i <= 5)   // āŒ COMPILE ERROR: ';' expected
// āœ… Fix: always end with semicolon
do {
    System.out.println(i);
    i++;
} while (i <= 5);  // āœ… Semicolon required

// āŒ MISTAKE 2: Forgetting to update loop variable (infinite loop)
int j = 1;
// do {
//     System.out.println(j);  // āŒ j never changes — infinite loop!
// } while (j <= 5);
// āœ… Fix: update inside body
do {
    System.out.println(j);
    j++;  // āœ…
} while (j <= 5);

// āŒ MISTAKE 3: Infinite loop from misplaced continue
int k = 0;
// do {
//     if (k % 2 == 0) continue; // āŒ k never incremented for evens — infinite!
//     System.out.println(k);
//     k++;
// } while (k < 10);
// āœ… Fix: increment BEFORE continue
do {
    k++;  // āœ… Update first
    if (k % 2 == 0) continue;
    System.out.println(k);
} while (k < 10);

// āŒ MISTAKE 4: Assuming body never runs when condition is false
int x = 100;
do {
    System.out.println("This ALWAYS runs at least once: x = " + x);
    x++;
} while (x < 5);  // Condition is false, but body already ran!
// Many beginners expect 'nothing to print' — but do-while always executes once

// āŒ MISTAKE 5: Not resetting inner variable in nested do-while
int row = 1;
// int col = 1;  // āŒ Initialized OUTSIDE outer loop — wrong!
do {
    int col = 1;  // āœ… Initialized INSIDE outer loop — resets each row
    do {
        System.out.print(col + " ");
        col++;
    } while (col <= row);
    System.out.println();
    row++;
} while (row <= 5);

// āŒ MISTAKE 6: Using assignment (=) instead of comparison (==) in condition
int flag = 0;
// do {
//     System.out.println("looping");
//     flag = 1;
// } while (flag = 0);  // āŒ COMPILE ERROR in Java (unlike C++) — good!
// Java does NOT allow assignment in boolean condition (unless type is boolean)
// āœ… Fix:
do {
    System.out.println("Correct condition check");
    flag = 1;
} while (flag == 0);  // āœ… Comparison operator

Bad Practices & Anti-Patterns — What Senior Developers Reject

These anti-patterns represent common misuses of do-while loops in professional Java code. Each one either causes bugs, hurts readability, or makes code harder to maintain and test.

🚫
Using Do-While When While Is Clearer

Reaching for do-while when a while loop is the natural fit makes code harder to understand. If there is any chance the body should not execute at all (e.g., iterating an empty collection, checking a condition that may be false from the start), use while. Do-while signals a specific contract to readers: 'this body always runs at least once.' Using it unnecessarily breaks that semantic expectation and confuses maintainers. Reserve do-while for cases where at-least-once execution is a genuine requirement.

🚫
Skipping Curly Braces

Java syntax technically allows a do-while with a single statement without braces: do System.out.println(x++); while(x < 5); — but this is dangerous and universally rejected in professional code. Adding a second statement below the do keyword while thinking it is inside the body is a silent logic bug. Always use curly braces for all do-while bodies, even single-statement ones. Every major Java style guide (Google, Oracle) mandates braces. The saved keystrokes are not worth the maintenance risk.

🚫
Complex Logic Inside the While Condition

Putting complex expressions in the while(condition) at the bottom of a do-while — especially expressions with side effects like method calls — makes the condition hard to reason about: do { ... } while (scanner.nextInt() > 0 && attempt++ < 3 && !isTimeout()); — the condition does too many things. Keep the while condition simple and boolean. Move side effects (reads, increments, method calls with consequences) into the body where they are visible and traceable. The while condition should express only the continuation criterion.

🚫
Using Do-While for Collections / Arrays

Do-while is not appropriate for iterating arrays or collections because it always processes the first element regardless of whether the collection is empty. If the array is empty, arr[0] in the body causes an ArrayIndexOutOfBoundsException. For collections and arrays, always use a for-each loop or a for loop with a bounds check — both correctly handle the empty case by not executing the body at all. Do-while should never be the first choice for data structure iteration.

🚫
Deeply Nested Do-While Without Extraction

Three or more levels of nested do-while loops create code that is nearly impossible to read, debug, and test. It is a strong signal to refactor: extract inner loops into separate methods with descriptive names, replace nested loops with data structures (HashMap, Stream) where applicable, or break the problem into smaller composable functions. Deep nesting is both a complexity smell and a performance warning — triple-nested do-while over n elements is O(n³).

🚫
Hardcoding Magic Numbers in Loop Conditions

Writing do { ... } while (attempt < 3); scatters the literal 3 as a magic number. If the business rule changes to 5 attempts, every such literal must be found and updated — a maintenance risk. Define named constants: private static final int MAX_ATTEMPTS = 3; then use: do { ... } while (attempt < MAX_ATTEMPTS); This makes the intent clear ('max attempt limit') and the update trivial (change one constant). SonarQube and other static analysis tools flag magic numbers as a code quality issue.

Real-World Production Code Examples — Do-While in Context

The following examples show idiomatic, production-grade Java do-while loop usage — patterns seen in real Spring Boot applications, CLI tools, and enterprise Java codebases.

ā˜• JavaAuthService.java — Login with Limited Attempts
package com.techsustainify.auth;

import java.util.Scanner;

public class AuthService {

    private static final int MAX_LOGIN_ATTEMPTS = 3;
    private static final int LOCKOUT_DURATION_MINUTES = 30;

    // āœ… Login flow with do-while — must attempt at least once
    public boolean authenticate(String correctUsername, String correctPassword) {
        Scanner sc = new Scanner(System.in);
        int attempts = 0;
        boolean authenticated = false;

        do {
            attempts++;
            System.out.printf("%nLogin Attempt %d of %d%n", attempts, MAX_LOGIN_ATTEMPTS);
            System.out.print("Username: ");
            String username = sc.nextLine().strip();
            System.out.print("Password: ");
            String password = sc.nextLine().strip();

            if (correctUsername.equals(username) && correctPassword.equals(password)) {
                authenticated = true;
                System.out.println("āœ… Login successful. Welcome, " + username + "!");
                logAuditEvent("LOGIN_SUCCESS", username);
                break;  // Exit on success
            } else {
                System.out.println("āŒ Invalid credentials.");
                logAuditEvent("LOGIN_FAILURE", username);
                if (attempts < MAX_LOGIN_ATTEMPTS) {
                    System.out.println("  " + (MAX_LOGIN_ATTEMPTS - attempts) + " attempt(s) remaining.");
                }
            }
        } while (attempts < MAX_LOGIN_ATTEMPTS);

        if (!authenticated) {
            System.out.printf("šŸ”’ Account locked for %d minutes after %d failed attempts.%n",
                             LOCKOUT_DURATION_MINUTES, MAX_LOGIN_ATTEMPTS);
            logAuditEvent("ACCOUNT_LOCKED", "unknown");
        }
        return authenticated;
    }

    private void logAuditEvent(String event, String user) {
        System.out.printf("[AUDIT] %s | user=%s | time=%s%n",
                         event, user, java.time.LocalDateTime.now());
    }
}
ā˜• JavaDataMigrationJob.java — Do-While for Batch Processing with Retry
package com.techsustainify.migration;

import java.util.ArrayList;
import java.util.List;

public class DataMigrationJob {

    private static final int BATCH_SIZE = 100;
    private static final int MAX_RETRIES = 3;

    // āœ… Paginated batch processing — do-while for guaranteed first execution
    public void migrateAllRecords() {
        int offset = 0;
        int totalMigrated = 0;
        List<String> batch;

        do {
            batch = fetchBatch(offset, BATCH_SIZE);
            if (!batch.isEmpty()) {
                int migrated = processBatchWithRetry(batch);
                totalMigrated += migrated;
                offset += batch.size();
                System.out.printf("Migrated batch: %d records. Total so far: %d%n",
                                 migrated, totalMigrated);
            }
        } while (batch.size() == BATCH_SIZE); // Continue while full batch returned

        System.out.println("āœ… Migration complete. Total records migrated: " + totalMigrated);
    }

    // āœ… Retry logic with do-while — attempt at least once
    private int processBatchWithRetry(List<String> batch) {
        int retryCount = 0;
        do {
            try {
                processBatch(batch);
                return batch.size();  // Success — return count
            } catch (Exception e) {
                retryCount++;
                System.out.printf("  Batch failed (attempt %d/%d): %s%n",
                                 retryCount, MAX_RETRIES, e.getMessage());
                if (retryCount < MAX_RETRIES) {
                    try {
                        Thread.sleep(1000L * retryCount); // Backoff
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            }
        } while (retryCount < MAX_RETRIES);

        System.out.println("  āŒ Batch failed after " + MAX_RETRIES + " attempts. Skipping.");
        return 0;
    }

    private List<String> fetchBatch(int offset, int limit) {
        // Simulated DB fetch — returns up to 'limit' records from 'offset'
        List<String> result = new ArrayList<>();
        int totalRecords = 250;
        for (int i = offset; i < Math.min(offset + limit, totalRecords); i++) {
            result.add("record_" + (i + 1));
        }
        return result;
    }

    private void processBatch(List<String> batch) {
        // Simulated processing — would insert into target DB
        System.out.println("  Processing " + batch.size() + " records...");
    }
}

Do-While Loop Flow Diagram — Visualizing Execution

This flowchart shows the execution flow of the do-while loop — highlighting how the body always executes first before the condition is ever evaluated, and contrasting it with the while loop's top-down condition check.

ā–¶ StartInitialization before loop
Enter — body first
āš™ļø Execute Loop BodyRuns FIRST — unconditionally
Check break
šŸ›‘ break encountered?Optional early exit from body
YES — exit immediately
ā­ļø continue encountered?Skip to condition check
YES — skip to condition
šŸ”„ Update Variablei++, i--, etc. inside body
Evaluate condition
šŸ” Evaluate Conditionwhile (condition); — checked AFTER
TRUE — repeat body
āœ… Exit LoopContinue with next statement

Code Execution Flow — from source to output

Java Do-While Loop Interview Questions — Beginner to Advanced

Do-while questions test your understanding of exit-controlled loops, the at-least-once guarantee, and the differences from while and for loops. These appear frequently in Java interviews at all levels.

Practice Questions — Test Your Do-While Knowledge

Challenge yourself with these practice questions. Attempt each independently before reading the answer — writing and tracing code by hand significantly improves retention and interview readiness.

1. What is the output? int i = 0; do { i++; if (i == 3) continue; System.out.print(i + " "); } while (i < 5);

Easy

2. What is the difference in output between these two loops? // Loop A int a = 5; while (a > 10) { System.out.println(a); a++; } // Loop B int b = 5; do { System.out.println(b); b++; } while (b > 10);

Easy

3. Write a do-while program to keep asking the user to guess a secret number (42) until they guess correctly. Show the number of attempts taken.

Medium

4. Trace the output: int a = 1, b = 2; do { System.out.println(a + " " + b); int temp = a + b; a = b; b = temp; } while (b <= 50);

Medium

5. Write a do-while loop to print all numbers from 1 to 100 that are divisible by both 3 and 5 (i.e., divisible by 15).

Easy

6. Identify and fix all bugs in this code: int i = 1 do { System.out.println(i); } while (i <= 5)

Easy

7. Write a program using nested do-while loops to print the following: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Medium

8. What is the output? Why does this not cause an infinite loop? int x = 0; do { x++; if (x % 2 == 0) continue; System.out.print(x + " "); } while (x < 8);

Hard

Conclusion — Do-While: The Exit-Controlled Loop with a Guarantee

The do-while loop is Java's most purpose-specific loop — it exists precisely for scenarios where the body must execute at least once before the condition can be evaluated. While it is the least commonly used of Java's three loops, it is the most correct and most readable choice when that at-least-once guarantee is genuinely needed.

Mastering do-while means knowing not just its syntax — the mandatory semicolon, the body-first execution, the bottom condition — but also its appropriate use cases: input validation, menu-driven programs, retry logic, game loops, and digit operations. Equally important is knowing when not to use it — for collection iteration, when the body may need to be skipped, or when a while or for loop expresses intent more clearly. Choosing the right loop type is a mark of an experienced Java developer.

ConceptKey PointWhen to Use
do-while syntaxdo { body } while(condition); — semicolon requiredAlways — no exceptions to the semicolon rule
Exit-controlledBody always executes at least onceWhen action must happen before condition check
vs while loopwhile checks first; do-while executes firstdo-while: at-least-once; while: zero-or-more
Input validationRead → validate → repeat if invalidClassic do-while pattern — no prime read needed
Menu programsShow menu → process → repeat until exitIdeal do-while use case
break in do-whileExits loop before condition checkEarly exit on success or error condition
continue in do-whileSkips to bottom condition checkSkip iterations; update variable BEFORE continue
Nested do-whileInner runs fully per outer iteration2D patterns; reset inner variable inside outer
do { } while(true)Intentional infinite loop — needs break/returnServer/event loops, REPL shells, retry logic
Magic numbersUse named constants in conditionMAX_ATTEMPTS instead of literal 3 — maintainable

Your next step: Java Arrays — where loops become the backbone of array traversal, searching, sorting, and manipulation. Everything you've learned about while and do-while loops applies directly to iterating arrays. ā˜•

Frequently Asked Questions — Java Do While Loop