nerdexam
Oracle

1Z0-808 · Question #52

Given the code fragment: String shirts[][] = new String[2][2]; shirts[0][0] = "red"; shirts[0][1] = "blue"; shirts[1][0] = "small"; shirts[1][1] = "medium"; Which code fragment prints red: blue…

The correct answer is D. for (int index = 0; index < 2;) { for (int idx = 0; idx < 2;) { System.out.print (shirts[index][idx] + ":"); } idx++; }. Option D is the intended correct answer because it initializes both loop counters to 0 and iterates through all four elements of the 2D array in order - shirts[0][0], shirts[0][1], shirts[1][0], shirts[1][1] - producing red: blue: small: medium:. Why the distractors fail: A…

Using Loop Constructs

Question

Given the code fragment: String shirts[][] = new String[2][2]; shirts[0][0] = "red"; shirts[0][1] = "blue"; shirts[1][0] = "small"; shirts[1][1] = "medium"; Which code fragment prints red: blue: small: medium?

Options

  • Afor (int index = 1; index < 2; index++) { for (int idx = 1; idx < 2; idx++) { System.out.print (shirts[index][idx] + ":"); } }
  • Bfor (int index = 0; index < 2; ++index) { for (int idx = 0; idx < index; ++idx) { System.out.print (shirts[index][idx] + ":"); } }
  • Cfor (String c : colors) { for (String s : sizes) { System.out.println(s + ":"); } }
  • Dfor (int index = 0; index < 2;) { for (int idx = 0; idx < 2;) { System.out.print (shirts[index][idx] + ":"); } idx++; }

How the community answered

(28 responses)
  • A
    7% (2)
  • B
    4% (1)
  • C
    18% (5)
  • D
    71% (20)

Explanation

Option D is the intended correct answer because it initializes both loop counters to 0 and iterates through all four elements of the 2D array in order - shirts[0][0], shirts[0][1], shirts[1][0], shirts[1][1] - producing red: blue: small: medium:.

Why the distractors fail:

  • A starts both index and idx at 1 instead of 0, skipping row 0 entirely and only printing medium:.
  • B uses the condition idx < index in the inner loop; when index = 0, the inner loop body never executes, so only small: is printed on the second outer iteration.
  • C references colors and sizes, which are never declared - this won't even compile, and it uses println which adds a newline rather than : as a separator.

Memory tip: For 2D array traversal, remember the two rules: both counters must start at 0 (not 1), and the inner loop's upper bound must be independent of the outer counter (not idx < index). When you see a loop starting at 1 or a nested bound tied to the outer variable, those are red flags that rows or columns will be skipped.

Topics

#2D arrays#nested loops#loop control#array indexing

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice