Java MCQ: What is the key difference between a while loop and a do-while loop in Java?
Answer:
Explanation:
The key difference between a while
loop and a do-while
loop in Java lies in the timing of the condition check. In a while
loop, the condition is checked before the loop body is executed. If the condition is false initially, the loop body will not execute at all. On the other hand, in a do-while
loop, the condition is checked after the loop body has been executed. This guarantees that the loop body is executed at least once, regardless of whether the condition is true or false.
Here’s an example of both loops:
// while loop example
int i = 0;
while (i < 0) {
System.out.println(i);
i++;
}
// do-while loop example
int j = 0;
do {
System.out.println(j);
j++;
} while (j < 0);
In the above example, the while
loop will not execute because the condition i < 0
is false. However, the do-while
loop will execute its body once before checking the condition.
This difference makes the do-while
loop useful when you want to ensure that the loop body runs at least once.
Reference links:
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html