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
