In Java, loops are essential control structures that allow you to execute a block of code repeatedly. While both the while loop and the do...while loop allow you to repeat a set of actions, they have slight differences in how they handle the loop's condition and when the loop executes. Understanding the differences between these two loops is key to using them effectively.
In this guide, we’ll explore both the while loop and the do...while loop, their syntax, differences, examples, and best practices.
A while loop in Java repeatedly executes a block of code as long as a specified condition remains true. The condition is evaluated before each iteration, which means if the condition is false from the beginning, the loop may not execute even once.
The syntax of the while loop consists of a condition that is evaluated before each loop iteration. If the condition is true, the loop’s body will execute. If it is false, the loop will terminate.
while (condition) {
// block of code to be executed
}
true
.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
A do...while loop in Java is similar to the while loop, but with one key difference: the condition is evaluated after the loop body is executed. This means the code inside the loop is guaranteed to run at least once, regardless of whether the condition is initially true or false.
do {
// block of code to be executed
} while (condition);
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
Feature | while Loop | do...while Loop |
---|---|---|
Condition Check | Before the loop starts (Pre-test) | After the loop executes (Post-test) |
Guaranteed Execution | May not execute at all if the condition is false initially. | Always executes at least once. |
Common Use Case | Used when the number of iterations is not known beforehand and the condition should be checked first. | Used when the loop should run at least once, regardless of the condition. |
In this example, we will print numbers from 1 to 5 using a while
loop.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
// Using while loop to print numbers 1 to 5
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
Explanation:
i <= 5
is checked before the loop executes. If the condition is true, the loop body is executed.i
is incremented in each iteration until it reaches 6, which causes the loop to stop.
1
2
3
4
5
Now, let’s use the do...while
loop to print numbers from 1 to 5.
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
// Using do...while loop to print numbers 1 to 5
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
Explanation:
i <= 5
is checked.i <= 5
is true, the loop will continue running.
1
2
3
4
5
while
loop is appropriate.do...while
loop is ideal.