What is the key difference between a while loop and a do-while loop in Java?

Welcome to Java MCQ (Mulitple Choice Question) series. In this post, we will see one more quiz question on Java Loops.

What is the key difference between a while loop and a do-while loop in Java? 

a) The syntax used to define the loop
b) The number of iterations performed
c) The condition check timing
d) The ability to use the break statement 

Answer:

c) The condition check timing 

Explanation:

The primary difference between a while loop and a do-while loop in Java is when the loop's condition is checked.

A while loop first checks the condition, and then the code inside the loop is executed if the condition is true. If the condition is false, the loop never runs.
int i = 5;
while(i < 5) {
    System.out.println(i);
    i++;
}
// This loop never runs because i is not less than 5.
A do-while loop first executes the code inside the loop and then checks the condition. This guarantees that the code inside the loop is executed at least once, regardless of whether the condition is true or false.
int i = 5;
do {
    System.out.println(i);
    i++;
} while(i < 5);
// This loop runs once, printing out "5", even though i is not less than 5.
So, to summarize, if you need to ensure the loop's code is executed at least once, you would use a do-while loop. Otherwise, you can use a while loop.

Comments