🔄 while loop in Java
When you don’t know how many times a block of code should run, the while loop is your best friend. 💡 It keeps running as long as a condition is true—making it perfect for real-world problems like taking user input, streaming data, or checking server status.
🧐 What is a while loop?
The while loop executes a block of code repeatedly until a condition becomes false.
👉 Syntax:
while(condition) {
// Code to be executed
}
🔍 How it Works
1️⃣ Condition is checked first (before entering loop).
2️⃣ If true → block of code runs.
3️⃣ If false → loop stops immediately.
4️⃣ After each execution, condition is re-checked.
✅ Example 1: Print Numbers from 1 to 5
int i = 1;
while(i <= 5) {
System.out.println("Number: " + i);
i++;
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
🚀 Why use while loop?
✔️ Best when the number of iterations is unknown.
✔️ Cleaner for input-driven tasks.
✔️ Useful in real-time programs (e.g., waiting for a condition to be met).
⚡ Popular Examples of while loop
1️⃣ Read Input Until User Exits
Scanner sc = new Scanner(System.in);
String input = "";
while(!input.equals("exit")) {
System.out.print("Enter text (type 'exit' to quit): ");
input = sc.nextLine();
}
2️⃣ Sum of Digits
int num = 1234, sum = 0;
while(num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of digits = " + sum);
Output:
Sum of digits = 10
3️⃣ Infinite Loop (⚠️ Be Careful!)
while(true) {
System.out.println("This will run forever!");
}
💡 Pro Tips
✅ Always make sure the condition will eventually be false → otherwise, infinite loop!
✅ Use break to exit loop early when needed.
✅ Use continue to skip certain iterations.
✨ Difference between for and while
| Feature | for loop | while loop |
|---|---|---|
| When to use | Known number of iterations | Unknown number of iterations |
| Syntax style | Compact (all in one line) | Cleaner for condition-driven tasks |
| Example use | Print table, arrays | User input, real-time checks |
✅ In short:
The while loop is perfect when you need a program to keep running until something happens. Mastering it helps you build interactive, real-world applications in Java. 🚀