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:

1
2
3
4
5

Example 2: Condition False at First

Even when the condition is false, the block executes once:


 

πŸ“Œ Output:

This will print at least once!

Β Example 3: User Input Loop (Practical Use Case)


 

πŸ“Œ This forces input until user enters a valid number.


πŸ” Key Difference: while vs do...while

Featurewhile Loopdo...while Loop
Condition checkedBefore executionAfter execution
Executes at least once?❌ Noβœ… Yes
Best used whenUnsure if loop should runLoop must run at least once

πŸ‘ Summary

  • do...while ensures code runs at least one time.

  • Useful for input validation or cases requiring an initial action.

You may also like...