Java MCQ: Which of the following loops is guaranteed to execute at least once?
a) for loop
b) while loop
c) do-while loop
d) None of the above
Answer:
c) do-while loop
Explanation:
The do-while
loop in Java is a type of loop that is guaranteed to execute at least once, regardless of whether the condition is true or false. This is because the condition is evaluated after the loop body has executed.
The syntax of a do-while
loop is as follows:
do { // code to be executed } while (condition);
This loop is particularly useful when the code inside the loop must be executed at least once before checking the condition. This contrasts with the for
and while
loops, where the condition is checked before the loop body is executed, so there is no guarantee that the loop will run at all if the condition is false.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html