Repeating a given set of statements is a common task for programmers, but sometimes the number of times a given statement is repeated is unknown. Java While Loop solves this. It gives a block of code the capability of repeated execution as long as a given condition is satisfied. Without this, your code could become unnecessarily long and complicated.
What is a Java While Loop?
A Java while loop is a control flow statement that repeats a set of instructions as long as a specified boolean condition remains true. You can think of it as a repeating if statement. The moment the condition becomes false, the loop stops automatically.
Java While Loop Syntax
while (condition) {
// code block to be executed
}
- Condition: A boolean expression that determines whether the loop continues.
- Code Block: Instructions executed repeatedly while the condition is true.
If the condition is false from the start, the code block never runs. This is why it is called a pre-test loop.
Java While Loop Example
Consider printing numbers from 1 to 5:
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
Execution explained:
- i starts at 1.
- The loop checks if i <= 5. True, so it prints Iteration: 1.
- i increases to 2.
- This repeats until i reaches 6, at which point the condition is false, and the loop stops.
Java Controlling Loops: Break and Continue
Java provides break and continue statements for more precise control.
Java While Loop Break
The break statement exits the loop immediately, even if the condition is still true.
Example: Stop the loop when i reaches 3.
int i = 0;
while (i < 10) {
if (i == 3) {
break;
}
System.out.println(i);
i++;
}
Java While Loop Continue
The continue statement skips the current iteration and proceeds with the next one.
Example: Skip the number 4 and continue printing:
int i = 0;
while (i < 6) {
i++;
if (i == 4) {
continue;
}
System.out.println(i);
}
Comparison While Loop vs. Do-While Loop
It is helpful to compare between the standard while loop from its variation, the do-while loop, to understand which to use in your DSA problems.
| Feature |
While Loop |
Do-While Loop |
| Condition Check |
Checked before execution |
Checked after execution |
| Min Iterations |
0 (may never run) |
At least 1 (always runs once) |
| Best Use Case |
When iterations are unknown |
When the code must run at least once |
The Infinite Loop Trap in Java While Loop
A common error that can be made with a Java while loop is failing to change the value in the while loop's conditional expression. A while loop will continue running indefinitely if the conditional expression never evaluates to false, which can cause your application to freeze or crash.
- Wrong: while (i < 5) { System.out.println(i); }
- Correct: Always be sure that a change occurs in the while loop's body, which will cause the conditional expression's exit condition to be met at some point.
Also Read :