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.
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
- Forgetting to update condition variable: Causes infinite loop
- Off-by-one in while condition:
while (i <= n)vswhile (i < n)matters - Confusing do-while with while: do-while always runs at least once
- Empty while body: Without braces, only first statement is in loop
- 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
Further Reading
- For Loops in Java - When iteration count is known: for loops provide clearer intent
- Break, Continue, and Labels - Loop control mechanisms
- Scanner and I/O Patterns - Real-world while loop usage for input reading
- Iterator Pattern and Collection Traversal - While loops for custom iteration
- Java Language Specification, SE 26, Chapter 14 -
whileanddostatement semantics
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.
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 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.