nerdexam
Oracle

1Z0-819 · Question #176

Given: ``java String[][] arr = { {"Red", "White"}, {"Black"}, {"Blue", "Yellow", "Green", "Violet"} }; for(int row = 0; row < arr.length; row++) { int column = 0; for(; column < arr[row].length…

The correct answer is D. [0,0]=Red[0,1]=White[1,0]=Black[2,0]=Blue[2,1]=Yellow[2,2]=Green[2,3]=Violet. Option D is correct because the inner loop uses arr[row].length - the actual length of each individual row - so it correctly steps through all 2 elements in row 0, 1 element in row 1, and all 4 elements in row 2, producing exactly the output shown. Why the distractors are…

Working with Arrays and Collections

Question

Given:
String[][] arr = {
 {"Red", "White"},
 {"Black"},
 {"Blue", "Yellow", "Green", "Violet"}
};

for(int row = 0; row < arr.length; row++) {
 int column = 0;
 for(; column < arr[row].length; column++) {
 System.out.println("[" + row + "," + column + "]=" + arr[row][column]);
 }
}
What is the result?

Options

  • A[0,0]=Red[0,1]=White[0,2]=Black,[1,0]=Blue[2,0]=Yellow[2,1]=Green[3,0]=Violet
  • B[0,0]=Red,[1,0]=Black,[2,0]=Violet
  • Cjava.lang.ArrayIndexOutOfBoundsException thrown
  • D[0,0]=Red[0,1]=White[1,0]=Black[2,0]=Blue[2,1]=Yellow[2,2]=Green[2,3]=Violet

How the community answered

(22 responses)
  • A
    5% (1)
  • B
    9% (2)
  • C
    5% (1)
  • D
    82% (18)

Explanation

Option D is correct because the inner loop uses arr[row].length - the actual length of each individual row - so it correctly steps through all 2 elements in row 0, 1 element in row 1, and all 4 elements in row 2, producing exactly the output shown.

Why the distractors are wrong:

  • A incorrectly places "Black" at [0,2] as if it were a third element of row 0, then misassigns "Blue" to row 1 - it treats the array as if all values are packed into a flat sequence rather than respecting row boundaries.
  • B only prints the first element of each row (column=0), which would happen if the inner loop condition were column < 1 - it ignores the remaining columns entirely.
  • C would be correct if the inner loop used a fixed column bound like arr[0].length (which is 2), causing an out-of-bounds error on row 2's 4 elements - but using arr[row].length keeps each iteration within bounds.

Memory tip: Whenever you see arr[row].length as the inner loop bound (not arr[0].length or a fixed number), the code is jagged-array safe - no exception will be thrown, and every element will be visited exactly once. Fixed bounds = danger; dynamic bounds = safe.

Topics

#2D arrays#jagged arrays#nested loops#array indexing

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice