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:

1
2
3
4
5

🔍 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:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Go!

⚠️ Infinite Loop Example (Don’t do this unless intended)


📌 This never stops.


 Example 3: Summation Loop


 

📌 Output:

Total: 15

🧠 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

You may also like...