Loops are one of the most powerful tools in programming. They let you run a block of code over and over again, saving you from writing repetitive code. In Java, there are several types of loops, and one of the most basic and useful ones is the
while loop.
In this article, we’ll focus only on the
Java while loop—what it is, how it works, when to use it, and how to avoid common mistakes. If you’re just starting with Java, mastering the while loop will make your code smarter and more efficient.
What is a While Loop?
A
while loop repeatedly executes a block of code
as long as a certain condition is true. Think of it like this:
“Keep doing this task while the condition is true.”
Here’s the basic syntax:
while (condition) {
// code to repeat
}
How it works:
- Java checks the condition.
- If the condition is
true
, it runs the block of code inside the loop.
- It goes back to step 1.
- If the condition becomes
false
, the loop stops.
Simple Example
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++;
}
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
What’s happening here?
- We start with
count = 1
.
- The loop runs while
count
is less than or equal to 5.
- Inside the loop, we print the count and then increase it by 1 using
count++
.
- Once
count
becomes 6, the condition count <= 5
is false, so the loop stops.
Why Use While Loops?
Use a while loop when:
- You don’t know exactly how many times a loop should run.
- The loop depends on a condition that might change during the loop.
This is different from a
for
loop, which is often used when you know how many times you want to repeat something.
Real-World Example: Password Checker
Let’s say you want to ask a user to enter a password until they get it right:
import java.util.Scanner;
public class LoginExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password = "";
while (!password.equals("java123")) {
System.out.print("Enter password: ");
password = scanner.nextLine();
}
System.out.println("Access granted!");
}
}
This loop keeps running until the user types
java123
. Once the condition becomes false (they got it right), it prints "Access granted!".
Common Mistake: Infinite Loops
If your condition never becomes false, the loop will run forever. This is called an
infinite loop, and it can crash your program.
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
// forgot to update i!
}
In this code,
i
never increases, so
i <= 5
is always true. The loop never ends.
To avoid this, always make sure:
- The condition will eventually become false.
- You're updating the variables used in the condition inside the loop.
While Loop vs. Do-While Loop
There's a similar loop called
do-while, which runs the code block
at least once, even if the condition is false at the start.
But with a regular
while
loop, the condition is checked
before the code runs. If it’s false from the beginning, the code won’t run at all.
Example:
int num = 10;
while (num < 5) {
System.out.println("This won't print.");
}
Since
10 < 5
is false, the loop is skipped entirely.
Loop Control: break and continue
You can control your while loop using these keywords:
🔸 break
– Exit the loop early
int i = 1;
while (i <= 10) {
if (i == 5) {
break; // stop the loop
}
System.out.println(i);
i++;
}
Output:
1
2
3
4
🔸 continue
– Skip to the next loop cycle
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue; // skip printing when i is 3
}
System.out.println(i);
}
Output:
1
2
3
4
Another Example: Countdown Timer
int countdown = 5;
while (countdown > 0) {
System.out.println("Countdown: " + countdown);
countdown--;
}
System.out.println("Blast off!");
This example counts down from 5 to 1 and then prints "Blast off!" at the end.
Summary and Best Practices
While loops are perfect when you don’t know exactly how many times a block of code needs to run. They're flexible and work well for user input, checking conditions, and repeating tasks based on changing variables.
Best practices:
- Always make sure the loop condition can eventually become false.
- Update loop control variables inside the loop.
- Use
break
and continue
wisely to control flow.
- Add comments to explain loop logic if it’s not obvious.
image quote pre code