Java Online Test - Loops

Welcome to our focused quiz on Java loops, designed to test your understanding of for, while, and do-while loops. These 10 multiple-choice questions (MCQs) explore how to control loop execution and utilize loop constructs effectively in Java. Perfect for beginners and seasoned programmers, this quiz will help you improve your loop control skills and deepen your Java knowledge.

1. Which loop is best used when the number of iterations is known beforehand?

a) while
b) do-while
c) for
d) None of the above

2. What is the output of the following code snippet?

int i = 0;
   while (i < 3) {
       System.out.println(i);
       i++;
   }
a) 0 1 2
b) 1 2 3
c) 0 1 2 3
d) 0 1

3. How do you ensure a loop runs at least once, regardless of the condition?

a) Use a for loop
b) Use a while loop
c) Use a do-while loop
d) Use an if statement

4. What is the output of the following code?

for (int i = 10; i > 0; i -= 2) {
       System.out.print(i + " ");
   }
a) 10 8 6 4 2 0
b) 10 8 6 4 2
c) 9 7 5 3 1
d) 10 9 8 7 6 5 4 3 2 1

5. What does the break statement do in a loop?

a) Pauses the loop
b) Continues to the next iteration
c) Terminates the loop
d) Decreases the loop counter

6. What is the output of the following code snippet?

int count = 0;
   for (int i = 5; i > 0; i--) {
       if (i == 3) continue;
       count++;
   }
   System.out.println(count);
a) 5
b) 4
c) 3
d) 2

7. How many times does the loop below execute?

int x = 5;
   while (x < 5) {
       x--;
   }
a) Infinite times
b) 0 times
c) 1 time
d) 5 times

8. What will be the output of the following code?

for (int i = 0; i < 5; i++) {
       if (i % 2 == 0) continue;
       System.out.print(i + " ");
   }
a) 0 2 4
b) 1 2 3 4
c) 1 3
d) 1 3 5

9. In Java, what does the following loop do?

do {
       System.out.println("Hello");
   } while (false);
a) Prints "Hello" once
b) Prints "Hello" infinitely
c) Does not compile
d) There is no output

10. What is the use of the continue statement in a loop?

a) It exits the loop
b) It skips the current iteration and continues with the next iteration
c) It repeats the current iteration
d) It checks the loop's condition

Comments