When writing programs, we often need to execute the same block of code multiple times.
For example:
- Reading records from a database
- Processing files line by line
- Displaying menu options until the user exits
- Traversing collections
- Waiting for a task to complete
Instead of writing the same code repeatedly, Java provides iterative statements, commonly known as loops.
In this article, we'll explore the while loop, understand how it works, learn its rules, and discuss common interview questions and beginner mistakes.
What Are Iterative Statements?
Iterative statements repeatedly execute a block of code as long as a specified condition remains true.
Java provides four looping constructs:
whiledo-whilefor- Enhanced
for(for-each)
Each loop has its own use cases.
In this article, we'll focus on the while loop.
What Is the while Loop?
A while loop repeatedly executes a block of code as long as its condition evaluates to true.
It is most useful when the number of iterations is unknown beforehand.
Typical examples include:
- Reading data until the end of a file
- Processing database records
- Traversing an iterator
- Waiting for user input
Syntax
while (condition) {
// loop body
}
The condition is checked before each iteration.
If the condition is false initially, the loop body never executes.
How the while Loop Works
The execution flow is simple:
- Evaluate the condition.
- If it is
true, execute the loop body. - Return to step 1.
- If the condition becomes
false, exit the loop.
Because the condition is checked first, a while loop may execute zero or more times.
Your First while Program
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
Output
1
2
3
4
5
Example: Printing Even Numbers
int number = 2;
while (number <= 10) {
System.out.println(number);
number += 2;
}
Output
2
4
6
8
10
Real-World Examples
The while loop is frequently used when working with APIs that continue until no more data is available.
Reading Database Records
while (resultSet.next()) {
// Process one record
}
Using an Iterator
while (iterator.hasNext()) {
Object value = iterator.next();
}
Reading an Enumeration
while (enumeration.hasMoreElements()) {
Object value = enumeration.nextElement();
}
These are common patterns you'll see in enterprise Java applications.
Rule 1: The Condition Must Be boolean
The expression inside a while loop must evaluate to a boolean value.
Correct
int count = 1;
while (count <= 5) {
count++;
}
The expression
count <= 5
returns either true or false.
Incorrect
while (1) {
}
Compile-time error
incompatible types:
int cannot be converted to boolean
Unlike C or C++, Java does not treat non-zero values as true.
Rule 2: Curly Braces Are Optional
If the loop body contains only one statement, braces may be omitted.
int count = 1;
while (count <= 3)
System.out.println(count++);
Output
1
2
3
Although valid, using braces is generally recommended for better readability.
Multiple Statements Require Braces
Incorrect
int count = 1;
while (count <= 3)
System.out.println(count);
count++;
The loop becomes infinite because only the first statement belongs to the loop.
Correct
int count = 1;
while (count <= 3) {
System.out.println(count);
count++;
}
Variable Declarations Need Braces
Incorrect
while (true)
int number = 10;
Compile-time error
variable declaration not allowed here
Correct
while (true) {
int number = 10;
break;
}
Empty Statement (;)
A semicolon by itself is a valid statement.
while (true);
System.out.println("Hello");
The loop never ends.
Therefore,
System.out.println("Hello");
is never reached.
Infinite Loops
A loop whose condition never becomes false is called an infinite loop.
Example
while (true) {
System.out.println("Running...");
}
This loop continues forever unless the program terminates externally.
Infinite loops are useful for:
- Server applications
- Event listeners
- Message consumers
- Game loops
Understanding the Unreachable Statement Rule
One of the most interesting Java interview topics is the unreachable statement rule.
Java's compiler reports an error whenever it can prove that a statement can never execute.
Case 1
while (true) {
}
System.out.println("Done");
Compile-time error
unreachable statement
The compiler knows the loop never exits.
Case 2
while (false) {
System.out.println("Hello");
}
Compile-time error
unreachable statement
Since the condition is always false, the loop body can never execute.
Case 3
int start = 10;
int end = 20;
while (start < end) {
}
System.out.println("Finished");
This compiles successfully.
Why?
The compiler cannot determine the values of start and end at compile time.
Although the program runs forever, the compiler doesn't know that.
The Effect of final
Now consider the same example using final.
final int start = 10;
final int end = 20;
while (start < end) {
}
System.out.println("Finished");
Compile-time error
unreachable statement
Why Does final Change Everything?
A final variable initialized with a constant becomes a compile-time constant.
The compiler effectively sees
while (10 < 20) {
}
which becomes
while (true) {
}
Since the compiler now knows the loop never ends, it reports the unreachable statement.
Execution Trace
int count = 1;
while (count <= 3) {
System.out.println(count);
count++;
}
| Iteration | count before | Condition | Output | count after |
|---|---|---|---|---|
| 1 | 1 | true | 1 | 2 |
| 2 | 2 | true | 2 | 3 |
| 3 | 3 | true | 3 | 4 |
| 4 | 4 | false | — | — |
Common Beginner Mistakes
Forgetting to Update the Loop Variable
Incorrect
int count = 1;
while (count <= 5) {
System.out.println(count);
}
The condition never changes.
Result:
Infinite loop.
Using Assignment Instead of Comparison
Incorrect
boolean running = false;
while (running = true) {
}
The assignment returns true, causing an infinite loop.
Accidentally Writing an Empty Loop
while (count <= 5);
System.out.println("Done");
The semicolon creates an empty loop.
The println() is outside the loop.
Using a Non-Boolean Condition
Incorrect
while (100) {
}
Only boolean expressions are allowed.
Best Practices
- Use a
whileloop when the number of iterations is unknown. - Always ensure the loop condition eventually becomes
false. - Prefer meaningful variable names such as
count,index, orremainingItems. - Use braces even for a single statement.
- Avoid writing complex conditions.
- Be careful not to accidentally place a semicolon after the
whilecondition.
Interview Questions
What is the difference between while and do-while?
A while loop checks the condition before executing the body.
A do-while loop checks the condition after executing the body.
Can a while loop execute zero times?
Yes.
If the condition is initially false, the loop body never executes.
Why does while (1) fail in Java?
Because Java requires a boolean expression.
Unlike C or C++, integers cannot be used as boolean values.
Why does adding final sometimes cause an unreachable statement error?
Because final variables initialized with constants become compile-time constants, allowing the compiler to determine that the loop is infinite.
Quick Memory Trick 🧠
Remember the word WHILE:
- W → Wait until the condition becomes false
- H → Header contains a boolean condition
- I → Iterates zero or more times
- L → Loop variable must change
- E → Exit when the condition becomes false
Key Takeaways
- A
whileloop repeats as long as its condition istrue. - The condition is evaluated before each iteration.
- The loop may execute zero or more times.
- The condition must evaluate to a boolean value.
- Curly braces are optional for a single statement but recommended.
- A misplaced semicolon creates an empty loop.
- Java detects unreachable statements during compilation.
-
finalvariables can change compile-time behavior by allowing the compiler to evaluate loop conditions.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)