Java While Loop
π Java While Loop
A while loop in Java is used to repeatedly execute a block of code as long as a condition is true.
β Syntax
π The loop runs only if the condition is true.
π Example 1: Basic While Loop
π Output:
π How It Works
| Step | Action |
|---|---|
| 1 | Check condition i <= 5 |
| 2 | If true β execute code |
| 3 | Increase i++ |
| 4 | Repeat until condition becomes false |
π Example 2: Countdown
π Output:
β οΈ Infinite Loop Example (Donβt do this unless intended)
π This never stops.
π Example 3: Summation Loop
π Output:
π§ When to Use a while Loop?
Use while when:
βοΈ You don’t know how many times the loop will run
βοΈ Condition controls the loop execution
