- What is a while Loop?
- Syntax of while Loop
- How while Loop Works With Example – Step by Step
- Explanation Step-by-Step
- Important Points to Remember about while loop
- 1. If the condition is never false, the loop becomes infinite.
- 2. You must change the loop variable inside the loop to avoid infinite execution.
- 3. while loop is useful when you don’t know in advance how many times the loop should run.
- 🌀 Infinite Loop Example
- Why infinite?
- 🛑 Breaking out of a while Loop
- 🔁 Skipping an Iteration with continue
- Real-life Example: Sum of First N Natural Numbers
- When to Use while Loop?
- Summary
Loops are a fundamental part of programming that allow us to execute a block of code multiple times. In Java, there are several types of loops – one of them is the while loop.
In this tutorial you will learn about the while loop in Java with clear explanations and real-world examples.
What is a while Loop?
A while loop is a control flow statement that allows code to be executed repeatedly based on a given condition.
It checks the condition first before executing the loop body. If the condition is true, the loop runs. If it is false, the loop stops.
Syntax of while Loop
while (condition) {
// code to be executed
}
condition: This is a boolean expression (trueorfalse).- The code inside the loop runs only if the condition is true.
- The condition is checked before the code inside the loop runs.
How while Loop Works With Example – Step by Step
Here’s a small code example of a while loop to understand how while loop works.
Example Code:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
System.out.println("Value of i: " + i);
i++;
}
System.out.println("Loop ended.");
}
}
Output
Value of i: 1
Value of i: 2
Value of i: 3
Loop ended.
Explanation Step-by-Step
Step 1:
Java starts from the main method.
int i = 1;
👉 A variable named i is declared and assigned value 1.
🧠 Memory: i = 1
Step 2:
while (i <= 3)
👉 Java checks: Is i (which is 1) less than or equal to 3?
✅ Yes → condition is true → enter the loop
Step 3 (First loop iteration):
System.out.println("Value of i: " + i);
👉 Prints: Value of i: 1
i++;
👉 i becomes 2 now
🧠 Memory: i = 2
Step 4:
Java goes back to the while condition:
while (i <= 3)
👉 Is i (2) less than or equal to 3?
✅ Yes → continue loop
Step 5 (Second loop iteration):
System.out.println("Value of i: " + i);
👉 Prints: Value of i: 2
i++;
👉 i becomes 3 now
🧠 Memory: i = 3
Step 6:
Back to the while condition:
while (i <= 3)
👉 Is i (3) ≤ 3?
✅ Yes → run loop again
Step 7 (Third loop iteration):
System.out.println("Value of i: " + i);
👉 Prints: Value of i: 3
i++;
👉 i becomes 4 now
🧠 Memory: i = 4
Step 8:
Back to the condition:
while (i <= 3)
👉 Is i (4) ≤ 3?
❌ No → condition is false → loop ends
Step 9:
Java moves to the next line after the loop:
System.out.println("Loop ended.");
👉 Prints: Loop ended.
Final Output of the Program:
Value of i: 1
Value of i: 2
Value of i: 3
Loop ended.
Important Points to Remember about while loop
1. If the condition is never false, the loop becomes infinite.
This means the loop will keep running forever, and your program will never stop.
Why? Because the while loop only stops when the condition becomes false
Example of an infinite loop:
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
// i is not changing, so condition is always true
}
In this code, the value of i is always 1, so the condition i <= 5 is always true.
Result: The program keeps printing i = 1 forever and never exits the loop. This is called an infinite loop.
2. You must change the loop variable inside the loop to avoid infinite execution.
To avoid infinite loops, you should always update the value that affects the condition, usually the loop variable.
Corrected version:
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++; // This updates i so the condition will eventually become false
}
Now, i increases by 1 on every iteration. After i reaches 6, the condition i <= 5 becomes false, and the loop stops.
Always make sure your loop is moving toward stopping.
3. while loop is useful when you don’t know in advance how many times the loop should run.
Use a while loop when the number of repetitions is not fixed or known beforehand. You let the condition control how long the loop runs.
Example: Keep asking the user for input until they type 0
Scanner sc = new Scanner(System.in);
int num = -1;
while (num != 0) {
System.out.print("Enter a number (0 to stop): ");
num = sc.nextInt();
}
Here:
- We don’t know how many numbers the user will enter.
- The loop keeps running until the user types 0.
- This is a perfect case for a while loop!
🌀 Infinite Loop Example
public class InfiniteLoop {
public static void main(String[] args) {
int i = 1;
while (i > 0) {
System.out.println("This is an infinite loop!");
}
}
}
Why infinite?
Because i is always greater than 0, and we never change its value!
🛑 Breaking out of a while Loop
You can use the break keyword to exit a loop when a certain condition is met.
public class BreakWhile {
public static void main(String[] args) {
int i = 1;
while (true) {
System.out.println("i: " + i);
if (i == 3) {
break; // exit loop
}
i++;
}
}
}
Output:
i: 1
i: 2
i: 3
🔁 Skipping an Iteration with continue
You can use the continue statement to skip the current iteration and move to the next one.
public class ContinueExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue; // skip when i is 3
}
System.out.println(i);
}
}
}
Output:
1
2
4
5
Real-life Example: Sum of First N Natural Numbers
import java.util.Scanner;
public class SumCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
System.out.println("Sum of first " + n + " numbers is: " + sum);
}
}
Output
Enter a positive number: 4
Sum of first 4 numbers is: 10
When to Use while Loop?
- When the number of iterations is not known in advance.
- When you want to wait for a condition to become true.
- When you need to read inputs until a certain value is entered (like 0 to stop).
Summary
| Feature | Description |
|---|---|
| Type of loop | Entry-controlled loop |
| Checks condition | Before executing body |
| Suitable for | Unknown number of iterations |
| Can be infinite | Yes, if not managed properly |
| Uses | Menus, input reading, real-time conditions |