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.
