Introduction
The do-while loop is a control flow statement in Java that executes a block of code at least once, and then repeatedly executes the block as long as a specified Boolean condition remains true. Unlike the while loop—which checks the condition before each iteration—the do-while loop checks the condition after the loop body has executed. This key difference makes it ideal for scenarios where the loop must run at least one time, such as menu-driven programs, input validation, or interactive user prompts. Understanding the syntax, behavior, and appropriate use cases of the do-while loop is essential for writing flexible and user-responsive Java applications.
1. Syntax of the do-while Loop
do {
// Code to execute
} while (condition);
Key Characteristics
- The loop body executes first, then the condition is evaluated.
- If the condition is
true, the loop repeats; iffalse, it terminates. - The semicolon (
;) after thewhilecondition is mandatory. - The condition must evaluate to a
booleanvalue.
2. How It Works: Step-by-Step Execution
- Execute the statements inside the
doblock. - Evaluate the
whilecondition. - If the condition is
true, go back to step 1. - If
false, exit the loop and continue with the next statement.
Because the condition is checked after the body, the loop always runs at least once, even if the condition is initially
false.
3. Example: Basic Usage
Counting from 1 to 3
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 3);
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Condition Initially False
int x = 5;
do {
System.out.println("This runs once, even though x > 3");
} while (x < 3);
Output:
This runs once, even though x > 3Contrast with
while: Awhile (x < 3)loop would not run at all.
4. Common Use Case: Input Validation
One of the most practical applications of do-while is validating user input until it meets certain criteria.
Example: Repeatedly Prompt Until Valid Input
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
boolean valid;
do {
System.out.print("Enter a number between 1 and 10: ");
if (scanner.hasNextInt()) {
number = scanner.nextInt();
valid = (number >= 1 && number <= 10);
if (!valid) {
System.out.println("Number out of range. Try again.");
}
} else {
System.out.println("Invalid input. Please enter an integer.");
scanner.next(); // Clear invalid token
valid = false;
}
} while (!valid);
System.out.println("You entered: " + number);
scanner.close();
}
}
This ensures the user is prompted at least once, and continues until valid input is received.
5. Menu-Driven Program Example
do-while is ideal for interactive menus that must display at least once.
import java.util.Scanner;
public class MenuExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Main Menu ---");
System.out.println("1. View Account");
System.out.println("2. Deposit Funds");
System.out.println("3. Exit");
System.out.print("Select an option: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Displaying account details...");
break;
case 2:
System.out.println("Processing deposit...");
break;
case 3:
System.out.println("Exiting program. Goodbye!");
break;
default:
System.out.println("Invalid option. Please choose 1, 2, or 3.");
}
} while (choice != 3);
scanner.close();
}
}
The menu displays before the user makes a choice, ensuring a natural user experience.
6. Comparison: while vs do-while
| Feature | while Loop | do-while Loop |
|---|---|---|
| Condition Check | Before loop body | After loop body |
| Minimum Executions | 0 | 1 |
| Use Case | When execution may not be needed | When execution is always needed |
| Syntax | while (cond) { ... } | do { ... } while (cond); |
When to Use Which?
- Use
whilewhen the loop might not need to run at all (e.g., processing a list that could be empty). - Use
do-whilewhen you must run the loop at least once (e.g., user prompts, initialization routines).
7. Infinite do-while Loops
An infinite loop can be created intentionally using do-while (true), often with a break statement for exit control.
do {
String input = getUserInput();
if (input.equals("quit")) {
break;
}
process(input);
} while (true);
Caution: Always ensure a clear exit condition to avoid hanging programs.
8. Best Practices
- Use
do-whileonly when the loop must execute at least once—don’t use it by default. - Ensure the condition variable is updated inside the loop to prevent infinite loops.
- Prefer
do-whilefor interactive input scenarios (menus, validation). - Keep the loop body simple and focused—extract complex logic into methods.
- Document the loop’s purpose, especially if the condition is non-obvious.
Conclusion
The do-while loop is a valuable control structure in Java that guarantees at least one execution of its body, making it uniquely suited for input validation, menu systems, and other interactive workflows. Its post-test nature distinguishes it from the while loop and fills a specific niche in program design. By understanding its syntax, behavior, and appropriate contexts, developers can write more intuitive and user-friendly applications. When applied correctly, the do-while loop enhances code clarity and ensures robust handling of user-driven or conditionally repeated tasks.