Java Do…While Loop
Java Do…While Loop
The do...while loop is similar to the while loop, but with one important difference:
π The code block executes at least once, even if the condition is false, because the condition is checked after the loop executes.
Syntax
π Note: A semicolon ; is required after the condition.
Example 1: Basic do…while Loop
π Output:
Example 2: Condition False at First
Even when the condition is false, the block executes once:
π Output:
Β Example 3: User Input Loop (Practical Use Case)
π This forces input until user enters a valid number.
π Key Difference: while vs do...while
| Feature | while Loop | do...while Loop |
|---|---|---|
| Condition checked | Before execution | After execution |
| Executes at least once? | β No | β Yes |
| Best used when | Unsure if loop should run | Loop must run at least once |
π Summary
do...whileensures code runs at least one time.Useful for input validation or cases requiring an initial action.
