while and do-while Loops in Java
Introduction
In Java programming, loops allow for the repeated execution of a block of code based on a boolean condition. While for loops are excellent for iterating over known ranges or collections, while and do-while loops excel in scenarios where the number of iterations is unknown in advance, and the loop must continue until a specific state or condition is met.
This guide explores the mechanics, use-cases, and critical differences between while and do-while loops.
1. The while Loop
The while loop evaluates a boolean condition before executing the block of code. If the condition is true, the code executes. Once the code finishes, the condition is evaluated again. This repeats until the condition becomes false.
Syntax
while (condition) {
// code block to execute
}
Because the condition is checked prior to execution, if the condition is false initially, the block of code will never execute. It is considered a pre-test loop.
Example: Reading Data
A classic use case for a while loop is reading from a stream or a file where the exact amount of data is unknown.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 'quit' to exit.");
String input = "";
while (!input.equals("quit")) {
input = scanner.nextLine();
System.out.println("You entered: " + input);
}
2. The do-while Loop
The do-while loop is a variation that executes the block of code first, and then evaluates the condition. If the condition is true, it loops back to the top.
Syntax
do {
// code block to execute
} while (condition);
(Note the mandatory semicolon at the end).
Because the code block runs before the condition is ever checked, the do-while loop guarantees that the code will execute at least once. It is considered a post-test loop.
Example: User Prompts
do-while loops are perfect for user input validation, where you must prompt the user at least once before checking if their input is valid.
int choice;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Menu:");
System.out.println("1. Play Game");
System.out.println("2. Exit");
System.out.print("Enter your choice (1-2): ");
choice = scanner.nextInt();
} while (choice < 1 || choice > 2);
System.out.println("Valid choice selected: " + choice);
3. Infinite Loops
An infinite loop occurs when the loop's terminating condition is never met. While usually a bug caused by failing to update a variable, infinite loops are sometimes created intentionally for background tasks, server polling, or game loops.
while (true) {
// Server listening for incoming network connections
Socket client = serverSocket.accept();
handleClient(client);
}
In intentional infinite loops, there is usually a blocking call (like accept()) or a break statement inside the loop based on external events.
4. Loop Control: break and continue
Like for loops, while loops support break and continue.
break: Immediately exits the loop, skipping the condition check and transferring execution to the code directly following the loop.continue: Immediately halts the current iteration, skipping the rest of the loop body, and jumps straight back to thewhilecondition evaluation for the next iteration.
Example with continue and break:
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Skip the rest of the loop for even numbers
}
if (i > 7) {
break; // Exit the loop entirely if i > 7
}
System.out.println("Odd number: " + i);
}
// Outputs: 1, 3, 5, 7
Warning: When using continue inside a while loop, ensure that the variable controlling the loop condition (e.g., i++) is updated before the continue statement executes. Otherwise, the loop will run infinitely!
5. Common Pitfalls
Off-by-One Errors
Careless initialization or updating can cause loops to execute one time too many or one time too few. Always trace the first and last iteration mentally.
The Infinite Loop Bug
Forgetting to modify the state that affects the condition.
int x = 0;
while (x < 5) {
System.out.println("x is " + x);
// Forgot to write x++; -> INFINITE LOOP!
}
Empty Loop Bodies
A stray semicolon after the while condition will create an empty loop body, leading to an infinite loop.
int y = 0;
while (y < 10); // Semicolon here makes the loop body empty!
{
y++;
}
Summary
- Use a
whileloop when you need to loop based on a condition and the code might not need to execute at all. - Use a
do-whileloop when the code block must execute at least once, such as in menu prompts or initial data fetching. - Always double-check your condition logic and state-updating statements to prevent accidental infinite loops.