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…
Question
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)- A7% (2)
- B4% (1)
- C18% (5)
- D71% (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
indexandidxat1instead of0, skipping row 0 entirely and only printingmedium:. - B uses the condition
idx < indexin the inner loop; whenindex = 0, the inner loop body never executes, so onlysmall:is printed on the second outer iteration. - C references
colorsandsizes, which are never declared - this won't even compile, and it usesprintlnwhich 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
Community Discussion
No community discussion yet for this question.