Java MCQ

Previous Java Multiple Choice Questions Next

Java Tricky Loops Questions

1

What is the output?
for(int i = 0; i < 5; i++); {
  System.out.println("Hello");
}

Correct Answer: B) Hello (printed once)

The semicolon after the for loop ends the loop statement. The code block that follows is just a regular block that executes once, printing "Hello" only one time.

2

What will be printed?
int i = 0;
while(i < 3) {
  System.out.print(i + " ");
  i++;
}
System.out.print(i);

Correct Answer: A) 0 1 2 3

The loop prints 0, 1, 2 (while i < 3). After the loop ends, i becomes 3 and the final print statement prints 3.

3

What is the output?
for(int i = 0; i < 3; i++) {
  for(int j = 0; j < 2; j++) {
    if(i == j) break;
    System.out.println(i + " " + j);
  }
}

Correct Answer: C) 1 0
2 0
2 1

When i=0, j=0: break (no print). When i=0, j=1: i≠j, print 0 1. When i=1, j=0: i≠j, print 1 0. When i=1, j=1: break. When i=2, j=0: i≠j, print 2 0. When i=2, j=1: i≠j, print 2 1.

4

What will be printed?
int i = 5;
do {
  System.out.print(i + " ");
  i--;
} while(i > 0);
System.out.print(i);

Correct Answer: A) 5 4 3 2 1 0

do-while executes at least once. It prints 5,4,3,2,1 (while i>0). When i becomes 0, loop stops and final print shows 0.

5

What is the output?
for(int i = 0; i < 5; i++) {
  if(i == 2) continue;
  System.out.print(i + " ");
}

Correct Answer: A) 0 1 3 4

When i=2, continue skips the print statement and moves to next iteration. So 2 is not printed.

6

What will be printed?
int i = 0;
while(i++ < 3) {
  System.out.print(i + " ");
}

Correct Answer: B) 1 2 3

Post-increment (i++) returns the original value then increments. So: i=0: 0<3 (true), i becomes 1, print 1. i=1: 1<3 (true), i becomes 2, print 2. i=2: 2<3 (true), i becomes 3, print 3. i=3: 3<3 (false), loop ends.

7

What is the output?
for(int i = 0; i < 3; i++) {
  System.out.print(i + " ");
  break;
}

Correct Answer: B) 0

The break statement exits the loop immediately after the first iteration, so only 0 is printed.

8

What will be printed?
int i = 0;
while(true) {
  if(i == 3) break;
  System.out.print(i + " ");
  i++;
}

Correct Answer: A) 0 1 2

The loop breaks when i becomes 3, so it prints 0, 1, 2 and stops before printing 3.

9

What is the output?
for(int i = 0; ; i++) {
  if(i > 2) break;
  System.out.print(i + " ");
}

Correct Answer: A) 0 1 2

Even though the for loop has no condition, the break statement stops the loop when i>2, so it prints 0, 1, 2.

10

What will be printed?
outer: for(int i = 1; i <= 2; i++) {
  inner: for(int j = 1; j <= 2; j++) {
    if(i == j) continue outer;
    System.out.println(i + " " + j);
  }
}

Correct Answer: D) 2 1

When i=1, j=1: continue outer skips to next i. When i=1, j=2: i≠j, print 1 2. When i=2, j=1: i≠j, print 2 1. When i=2, j=2: continue outer.

Previous Java Multiple Choice Questions Next