The while loop is used when a program needs to repeat a block of code as long as a condition remains true. Unlike a for loop, a while loop is often useful when the exact number of repetitions is not known before the program starts.
Why Do We Need a while Loop?
Consider a login system. The program may continue asking for a password while the entered password is incorrect. The number of attempts may vary, so the program can simply continue while a particular condition is true.
A while loop repeatedly executes a block of code as long as its condition evaluates to true.
Real-World Analogy
Imagine filling a water tank. You keep adding water while the tank is not full.
While tank is not full
Add water
You may not know exactly how many actions will be required. The important part is the condition: continue while the tank is not full.
Basic Syntax
while (condition) {
// code to repeat
}
Java checks the condition before every iteration. If the condition is true, the loop body executes. After the body finishes, Java checks the condition again.
Simple Example
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
The variable i starts at 1. Java checks whether i <= 5. Since the condition is true, the number is printed and i is increased by 1.
This continues until i becomes 6. At that point, the condition becomes false and the loop stops.
How the while Loop Works
- The loop condition is checked first.
- If the condition is true, the loop body executes.
- The loop body performs its required operation.
- The condition is checked again.
- The process continues until the condition becomes false.
Remember: A while loop checks its condition before executing the body. Therefore, the loop body may execute zero times.
Example: Printing Numbers
int number = 1;
while (number <= 10) {
System.out.println(number);
number++;
}
This loop prints numbers from 1 to 10. The variable number acts as the loop counter and is increased after every iteration.
Example: Countdown
int count = 5;
while (count >= 1) {
System.out.println(count);
count--;
}
The loop starts at 5 and decreases the value after each iteration. When count becomes 0, the condition count >= 1 becomes false and the loop stops.
while Loop That Executes Zero Times
Because the condition is checked before the body, the loop may never execute.
int number = 10;
while (number < 5) {
System.out.println(number);
}
The condition is false immediately because 10 is not less than 5. Therefore, Java skips the loop body completely.
Updating the Loop Variable
A common pattern with a while loop is to modify a variable that affects the loop condition.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
The i++ statement is important because it moves the loop toward its stopping condition. Without an appropriate update, the loop may continue forever.
Always check whether the variables involved in the loop condition are eventually changed. Otherwise, you may accidentally create an infinite loop.
Example: Sum of Numbers
int i = 1;
int sum = 0;
while (i <= 5) {
sum = sum + i;
i++;
}
System.out.println("Sum: " + sum);
The loop repeatedly adds the current value of i to sum. After processing numbers 1 through 5, the final sum is 15.
while Loop vs for Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Best suited for | Known or clearly controlled repetition. | Repetition based mainly on a condition. |
| Initialization | Usually written in the loop header. | Usually written before the loop. |
| Condition | Written in the loop header. | Written in the loop header. |
| Update | Usually written in the loop header. | Usually written inside the loop body. |
When Should You Use while?
- When the number of iterations is not known in advance.
- When repetition depends primarily on a condition.
- When the loop should continue until some state changes.
- When placing initialization and update outside the loop header makes the logic clearer.
Common Beginner Mistakes
- Forgetting to update the variable used in the condition.
- Writing a condition that can never become false.
- Updating the variable incorrectly and getting unexpected results.
- Assuming the loop body will always execute at least once.
- Changing the condition-related variable in multiple places and making the loop difficult to understand.
Best Practices
- Keep the loop condition simple and readable.
- Make the update operation easy to identify.
- Ensure the loop has a clear path toward termination.
- Avoid unnecessary changes to the condition-related variable.
- Choose a for loop when initialization, condition, and update naturally belong together.
Interview Insight
A common interview question is: “Can a while loop execute zero times?” Yes. Because the condition is evaluated before the loop body, a false condition at the beginning causes Java to skip the body entirely.
Quick Revision
| Concept | Key Point |
|---|---|
| while loop | Repeats code while a condition remains true. |
| Condition | Checked before every iteration. |
| Initialization | Usually written before the loop. |
| Update | Usually changes the condition-related variable inside the loop. |
| Zero iterations | Possible when the initial condition is false. |
| Infinite loop | Can occur when the condition never becomes false. |
The while loop is a natural choice when repetition depends on a condition rather than a fixed number of iterations. It checks that condition before every pass, which makes it flexible but also requires careful control of the variables involved. The next loop, do-while, changes one important detail: it executes the loop body before checking the condition.
