Java Do While Loop: Syntax and Usage
Learn the java do while loop syntax, how it differs from while, and when to use it for guaranteed single execution in Java.
The java do while loop is the only loop construct in Java that guarantees the loop body executes at least once before the condition is evaluated. This behavior makes it distinct from the while loop, which checks the condition before entering the body. For developers who need to run a block of code unconditionally at least once, the do-while loop is the correct tool.
The do-while Loop in Java: Core Syntax
The syntax is straightforward:
do { // loop body } while (condition);
The do keyword starts the block, and the while keyword with a condition follows after the closing brace. A semicolon is required after the condition. The condition is a boolean expression that is evaluated after each execution of the body. If the condition evaluates to true, the body runs again; if false, control passes to the statement after the loop.
Here is a minimal example that prints numbers from 0 to 2:
int i = 0; do { System.out.println(i); i++; } while (i < 3);
Even if i starts at 3, the body still runs once because the condition is not checked until after the first iteration. This is the defining characteristic of the do-while loop.
How the do-while Loop Differs from while
The while loop evaluates its condition before the first iteration. If the condition is initially false, the body never executes. In contrast, the do-while loop always executes the body at least once. This difference matters when the loop body must run before any condition can be meaningfully evaluated.
| Characteristic | while loop | do-while loop |
|---|---|---|
| Condition check | Before body | After body |
| Minimum executions | 0 | 1 |
| Typical use | Pre-validated conditions | Post-validation or prompt-based flows |
For example, reading input from a user until a valid value is provided is a natural fit for do-while because you must prompt at least once before you can validate the response.
Practical Example: User Input Validation
A common use case is repeatedly asking for input until it meets a requirement. Consider a simple console application that asks for a positive integer:
Scanner scanner = new Scanner(System.in); int number; do { System.out.print("Enter a positive integer: "); while (!scanner.hasNextInt()) { System.out.println("That's not an integer."); scanner.next(); } number = scanner.nextInt(); } while (number <= 0);
In this example, the inner while loop handles non-integer input, but the outer do-while ensures the prompt is shown at least once. The condition number <= 0 is evaluated after the first input attempt. If the user enters -5, the loop repeats; if they enter 7, it exits. This pattern is cleaner than a while loop that would require initializing number to a sentinel value before the first check.
When to Use do-while Over Other Loops
The do-while loop is not a universal replacement for for or while. Use it when the loop body must execute at least once regardless of the initial state. Typical scenarios include:
- Menu-driven programs where the menu must display before the user selects an option.
- Retry logic where an operation must be attempted before deciding whether to retry.
- Polling a resource that may not be ready, but you need to check at least once.
If the loop body is meaningful only when a condition is already true, use while or for. For instance, iterating over a collection with a known size is better done with an enhanced for loop. The do-while loop is not designed for counting iterations with a known bound; it shines when the number of iterations is unknown and the first execution is required.
Common Mistakes and Edge Cases
One frequent mistake is forgetting the semicolon after the while condition. The compiler will report a syntax error, but the message can be confusing if the semicolon is omitted. Always include it.
Another issue is relying on the do-while loop when the condition should be checked before the body. For example, if you are iterating over an empty collection, a do-while loop will attempt to access an element that does not exist, causing an exception. Consider this code:
List<String> items = Collections.emptyList(); int index = 0; do { System.out.println(items.get(index)); // Throws IndexOutOfBoundsException index++; } while (index < items.size());
The body runs once even though the list is empty. If the logic depends on the collection having at least one element, a while loop with an upfront !isEmpty() check is safer.
Variable scope inside the loop body is also worth noting. Variables declared inside the do block are local to that block and cannot be referenced in the while condition. For example:
do { int x = 5; } while (x > 0); // Compilation error: x cannot be resolved
The condition can only reference variables declared before the loop or fields accessible from the enclosing scope.
Performance and Maintainability Considerations
From a performance perspective, the do-while loop has no inherent advantage over while in terms of execution speed. The JVM can optimize both constructs similarly. The choice should be based on readability and correctness rather than micro-optimization.
A maintainability concern is that do-while loops can obscure the loop's exit condition because the condition appears at the bottom. When reading code, developers often look at the top of a loop to understand its behavior. With do-while, the condition is not visible until the end, which can lead to misunderstandings if the loop body is long. To mitigate this, keep the loop body short and place the condition as close to the body as possible. If the body exceeds a few lines, consider extracting it into a method or using a while loop with a sentinel value if the first execution is not strictly required.
Another edge case is the use of break and continue inside a do-while loop. break exits the loop entirely, while continue jumps to the condition evaluation. This behavior is consistent with other loops, but it can be surprising because the condition is evaluated after continue. For example:
int i = 0; do { i++; if (i % 2 == 0) { continue; } System.out.println(i); } while (i < 5);
This prints 1, 3, and 5. The continue skips the print for even numbers, but the loop still increments i and evaluates the condition. Understanding this flow is essential for debugging loops with control statements.
When using do-while in a multi-threaded context, remember that the loop condition is not atomic unless synchronized. If multiple threads modify the variables used in the condition, you need explicit synchronization or use higher-level concurrency primitives. The loop itself does not provide any thread safety.
Finally, consider whether a do-while loop is the clearest expression of your intent. In many cases, a while loop with a pre-initialized variable is just as readable and avoids the subtle guarantee of at least one execution. Reserve do-while for situations where that guarantee is a core requirement, not a side effect.