Java OCA OCP Practice Question 1782

Question

Given the following code fragment, which of the following lines will be a part of the output?.

outer:
for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 2; j++) {
    if (i == j) {
      continue outer;
    }
    System.out.println("i=" + i + ", j=" + j);
  }
}

Select the two correct answers.

  • (a) i=1, j=0
  • (b) i=0, j=1
  • (c) i=1, j=2
  • (d) i=2, j=1
  • (e) i=2, j=2
  • (f) i=3, j=3
  • (g) i=3, j=2


(a) and (d)

Note

"i=1, j=0" and "i=2, j=1" are part of the output.

The variable i iterates through the values 0, 1, and 2 in the outer loop, while j toggles between the values 0 and 1 in the inner loop.

If the values of i and j are equal, the printing of the values is skipped and the execution continues with the next iteration of the outer loop.

The following can be deduced when the program is run: variables i and j are both 0 and the execution continues with the next iteration of the outer loop.

"i=1, j=0" is printed and the next iteration of the inner loop starts.

Variables i and j are both 1 and the execution continues with the next iteration of the outer loop.

"i=2, j=0" is printed and the next iteration of the inner loop starts.

"i=2, j=1" is printed, j is incremented, j < 2 fails, and the inner loop ends.

Variable i is incremented, i < 3 fails, and the outer loop ends.




PreviousNext

Related