While and Do-While Loops in Java

Learn Java while and do-while loops: pre-test vs post-test iteration, infinite loops, loop termination strategies, and when to choose each loop type.

published: reading time: 13 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn Java while and do-while loops: pre-test vs post-test iteration, infinite loops, loop termination strategies, and when to choose each loop type.

While and Do-While Loops in Java

While and do-while loops provide iterative control flow in Java. The key difference is when the condition is evaluated: while checks before the loop body (pre-test), do-while checks after (post-test), guaranteeing at least one execution.

Introduction

A while loop checks its condition before each iteration, so its body can run zero times. A do-while loop checks after the body, so it always runs at least once. Choose based on that difference and on which form makes the exit condition easiest to read. Loop speed is rarely a useful selection criterion; compiler and runtime optimizations vary by implementation and workload.

Use these loops when the next step depends on a condition or incoming data rather than a known count. A for loop often reads better for counted iteration, and an enhanced for loop is usually clearer for traversing a collection. The main bug to watch for is an exit condition that never changes; for loops that wait on external state, use the right synchronization or blocking API instead of repeatedly polling without a plan.

The examples show the zero-or-more and at-least-once guarantees, input validation, and common exit conditions. They also point out where a loop that reads shared state needs synchronization.

When to Use / Not to Use

Use while loops when:

  • Number of iterations is unknown beforehand
  • Iterating until a condition becomes false
  • Processing input that may have zero elements
  • Waiting for external state changes

Use do-while loops when:

  • Loop body must execute at least once
  • User input validation requiring at least one prompt
  • Menu-driven programs where the menu must display before checking exit
  • Initialization followed by conditional continuation

Do not use while/do-while when:

  • Number of iterations is known—use for loop instead
  • Traversing collections—use enhanced for-each
  • The termination condition is based on index—use for loop

Diagram: While Loop (Pre-test)

flowchart TD
    A1["Start"] --> B1{"Condition?"}
    B1 -->|true| C1["Execute body"]
    C1 --> B1
    B1 -->|false| D1["Exit"]

Diagram: Do-While Loop (Post-test)

flowchart TD
    A2["Start"] --> C2["Execute body"]
    C2 --> B2{"Condition?"}
    B2 -->|true| C2
    B2 -->|false| D2["Exit"]

Code Snippet: Loop Patterns

This demo uses List.of, available since Java 9.

import java.util.Scanner;

public class WhileDoWhileDemo {
    public static void main(String[] args) {
        // While loop - zero or more iterations
        int count = 0;
        while (count < 5) {
            System.out.println("While iteration: " + count);
            count++;
        }

        // While with unknown iterations (reading input)
        java.util.List<String> inputs = new java.util.ArrayList<>();
        Scanner scanner = new Scanner("apple\nbanana\nstop\n");
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.equals("stop")) {
                break; // Exit loop early
            }
            inputs.add(line);
        }
        System.out.println("Collected: " + inputs);

        // Do-while - at least one iteration
        int userChoice;
        do {
            System.out.println("\nMenu:");
            System.out.println("1. Start");
            System.out.println("2. Settings");
            System.out.println("3. Exit");
            userChoice = 2; // Simulated choice
        } while (userChoice < 1 || userChoice > 3);
        System.out.println("Valid choice: " + userChoice);

        // Infinite loop with termination condition
        System.out.println("\nSimulated countdown:");
        int countdown = 5;
        while (true) {
            System.out.println(countdown);
            countdown--;
            if (countdown < 0) {
                System.out.println("Blastoff!");
                break; // Exit infinite loop
            }
        }

        // While with continue (skipping iterations)
        System.out.println("\nSkip even numbers:");
        int num = 0;
        while (num < 10) {
            num++;
            if (num % 2 == 0) {
                continue; // Skip even numbers
            }
            System.out.println("Odd: " + num);
        }

        // Nested while loops
        System.out.println("\nMultiplication table:");
        int row = 1;
        while (row <= 3) {
            int col = 1;
            while (col <= 3) {
                System.out.print(row * col + "\t");
                col++;
            }
            System.out.println();
            row++;
        }
    }
}

Input validation with a do-while loop

This runnable example uses OptionalInt (Java 8+), prompts at least once, rejects non-numeric and out-of-range input, and exits cleanly when standard input ends. The loop stops when validChoice becomes true.

import java.util.OptionalInt;
import java.util.Scanner;

public class ChoicePrompt {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            OptionalInt choice = readChoice(input);
            if (choice.isPresent()) {
                System.out.println("Accepted: " + choice.getAsInt());
            } else {
                System.out.println("No input; exiting.");
            }
        }
    }

    private static OptionalInt readChoice(Scanner input) {
        int choice = 0;
        boolean validChoice = false;

        do {
            System.out.print("Choose 1, 2, or 3: ");
            if (!input.hasNextLine()) {
                return OptionalInt.empty();
            }

            String line = input.nextLine();
            try {
                choice = Integer.parseInt(line.trim());
                validChoice = choice >= 1 && choice <= 3;
            } catch (NumberFormatException ex) {
                choice = 0;
                validChoice = false;
            }

            if (!validChoice) {
                System.out.println("Enter an integer from 1 to 3.");
            }
        } while (!validChoice);

        return OptionalInt.of(choice);
    }
}

For input nope, then 4, then 2, the program rejects the first two entries and ends with Accepted: 2. At end-of-file, it returns without waiting for another line.

Failure Scenarios

Scenario Problem Solution
Infinite loop Condition never becomes false Ensure update statement changes condition
Off-by-one Loop executes one time too many/few Verify termination condition
do-while without braces Only first statement is in loop Always use braces
NullPointerException Accessing null reference in condition Check for null before loop

Trade-off Table

Loop Type Guarantee Use When
while 0+ iterations Unknown iteration count, may be empty
do-while 1+ iterations Must execute at least once
for 0+ iterations Known count or index-based
for-each 0+ iterations Collection traversal

Observability Checklist

  • Log loop iteration count for long-running loops
  • Add timeout mechanism for loops that may not terminate
  • Instrument termination conditions for debugging
  • Monitor while loops that access external resources (prevent resource exhaustion)
  • Add integration tests for empty input handling

Security Notes

  • Infinite loops: Can cause CPU starvation and DoS; implement iteration limits
  • Resource leaks: Ensure loops accessing I/O have proper cleanup in finally blocks
  • Timing attacks: Constant-time comparison for conditions that may leak timing info

Pitfalls

  1. Forgetting to update condition variable: Causes infinite loop
  2. Off-by-one in while condition: while (i <= n) vs while (i < n) matters
  3. Confusing do-while with while: do-while always runs at least once
  4. Empty while body: Without braces, only first statement is in loop
  5. NullPointerException in condition: Always check for null before looping on collections

Quick Recap

  • while: Pre-test loop, executes 0+ times
  • do-while: Post-test loop, executes 1+ times
  • Use while when iterations may be zero
  • Use do-while when at least one iteration is guaranteed
  • Always ensure the condition eventually becomes false to avoid infinite loops
  • Use break/continue for flow control within loops

Interview Questions

1. What is the difference between while and do-while loops?
While is a pre-test loop—it checks the condition before executing the body. The body may execute zero times if the condition is initially false. Do-while is a post-test loop—it executes the body first, then checks the condition. Do-while always executes at least once."

2. How do you create an infinite loop in Java?
Create an unconditional loop with `while (true) { ... }` or `for (;;) { ... }`. Its body runs until a `break`, `return`, or exception exits it. The generated bytecode is a compiler detail, so choose the form that makes intent clearer and keep the exit path easy to find."

3. When should you prefer while over for loop?
Prefer while when: (1) the number of iterations is not known upfront, (2) termination depends on a condition that changes inside the loop body, (3) you're waiting for an external state change. Use for when you have a known count or index-based iteration."

4. What causes an infinite loop and how do you prevent it?
An infinite loop is caused when the termination condition never becomes false. Common causes: forgetting to update the condition variable, increment that doesn't affect the condition, or comparing against the wrong value. Prevention: always update condition variables, use defensive checks, add timeout mechanisms for production code."

5. What is a sentinel value in loop termination?
A sentinel value is a special value that signals the end of input or loop termination. Example: reading lines until encountering "quit". The sentinel is processed as data but triggers loop exit when detected. Use clearly defined sentinel values and document them to avoid accidental early termination."

6. What is the key difference between a pre-test and post-test loop?
Pre-test (while) evaluates the condition before each iteration—if false initially, the body never runs. Post-test (do-while) evaluates after each iteration—the body always runs at least once before the condition is checked. Choose based on whether zero executions is a valid scenario."

7. How does `break` behave in nested while loops?
A `break` statement only exits the innermost enclosing loop. If you need to exit an outer loop from within nested while loops, use a labeled break (`break outerLabel;`) or a flag variable to signal the outer loop to terminate."

8. What is the difference between `break` and `return` in a loop?
`break` exits only the innermost loop or switch. `return` exits the entire method, including all loops. Use `break` when you want to stop the current loop but continue with method execution. Use `return` when the loop's termination also means the method has nothing more to do."

9. Can you use while loops to process streams incrementally?
Yes, while loops can process stream-like data (reading lines from a file, consuming from a queue). However, for collection traversal, the enhanced for-each or Stream API often provides cleaner code. While is best when termination depends on data content, not just exhaustion."

10. Why might `do-while` be preferred over `while` for menu-driven programs?
Menu-driven programs need to display the menu at least once before checking if the user wants to exit. A `do-while` loop handles this naturally: `do { displayMenu(); choice = getInput(); } while (choice != EXIT);`. A `while` loop would need to duplicate the menu display before the loop."

11. What is the difference between `continue` and `break` in a while loop?
`continue` skips to the next iteration of the loop (re-evaluates the condition immediately). `break` exits the loop entirely. In a while loop, after `continue`, the condition is re-evaluated. In do-while, `continue` jumps to the condition check directly."

12. What happens if a while loop's condition is initially false?
The loop body never executes. This is the "zero or more" guarantee of pre-test loops. This is desirable when the input might be empty, no items match, or the data hasn't arrived yet. If you need at least one execution, use do-while."

13. How do you implement a do-while loop that reads input until valid?
A `do-while` loop fits when you must prompt at least once. The runnable example in the input-validation section handles end-of-input and repeats until the user enters a number from 1 to 3."

14. What is the difference between while(true) and for(;;) in Java?
Both forms express a loop without a built-in terminating condition. Choose the one that makes the intent clear to your readers, and make the actual exit path easy to find. Generated code is an implementation detail."

15. How do you prevent resource exhaustion from infinite loops in production?
Add iteration limits or timeout mechanisms: check iteration count every N iterations and throw if exceeded, set a wall-clock timeout, use a ScheduledExecutorService to cancel long-running loops. For loops processing external data (file reads, network streams), implement heartbeat checks and fail-fast on timeout."

16. What are common patterns for loop termination in real-world Java applications?
Sentinel values (read until "quit"), EOF signals (file reading returns null), condition flags (boolean stop variable set by another thread), timeout expiration, result saturation (no improvement for N iterations), and collection exhaustion (iterator.hasNext() returns false). Choose the pattern that matches your data source semantics."

17. How does a while loop interact with the Java Memory Model for variable visibility?
If a while loop reads a variable written by another thread (e.g., a flag `while (!done)`), the read may be cached and the loop runs forever if `done` is not volatile or final. In Java's memory model, without proper synchronization, visibility of changes from one thread to another is not guaranteed. Use volatile, synchronized, or atomic variables for flags read/written across threads."

18. What is the difference between a counted loop and a conditional loop?
A counted loop (for, enhanced for) uses an iteration counter and is appropriate when the number of iterations is known upfront. A conditional loop (while, do-while) uses a boolean condition and is appropriate when the termination depends on state rather than a count. Using while when you have a known count (like iterating an array) is less clear than using for."

19. How does try-with-resources interact with while loops for resource cleanup?
For resources accessed in a while loop, wrap the resource acquisition in try-with-resources: `try (Scanner sc = new Scanner(file)) { while (sc.hasNextLine()) { process(sc.nextLine()); } }` — the Scanner is automatically closed when the block exits, even if an exception occurs in the loop body. This pattern ensures resources are not leaked regardless of how the loop terminates."

20. What is the effect of exception handling on while loop termination?
If an exception is thrown in the loop body and not caught, the loop terminates and the exception propagates. The finally block (if any) executes before propagation. For loops that must clean up regardless of how they exit, use try-finally or try-with-resources. An uncaught exception in a background thread does not affect the main thread's loops."

Further Reading

Conclusion

While and do-while loops fill the gap when iteration count is unknown—the key difference is that do-while guarantees at least one execution. Use while when zero iterations are valid (empty input, unfulfilled conditions). Use do-while when the loop body must run at least once (menu display, user prompt).

Infinite loops with break are a common pattern for event-driven loops and game loops. Always ensure the break condition is guaranteed to trigger, or add a timeout mechanism to prevent CPU starvation in production systems.

These loops work seamlessly with break, continue, and labels for control flow. When you know the iteration count upfront, for loops often provide clearer intent. For traversing collections, the enhanced for-each is usually the best choice.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals