nerdexam
Oracle

1Z0-808 · Question #62

Given: public class Test { public static void main(String[] args) { String[][] chs = new String[2][]; chs[0] = new String[2]; chs[1] = new String[5]; int i = 97; for (int a = 0; a < chs.length; a++)…

The correct answer is A. 97 98 99 100 null null null. Option A is correct because the inner loop uses chs.length (which is 2, the number of rows) instead of chs[a].length (the number of columns per row). This means the fill loop only writes to indices 0 and 1 of chs[1], leaving its remaining three elements as null. When the print…

Creating and Using Arrays

Question

Given: public class Test { public static void main(String[] args) { String[][] chs = new String[2][]; chs[0] = new String[2]; chs[1] = new String[5]; int i = 97; for (int a = 0; a < chs.length; a++) { for (int b = 0; b < chs.length; b++) { chs[a][b] = "" + i; i++; } } for (String[] ca : chs) { for (String c : ca) { System.out.print(c + " "); } System.out.println(); } } } What is the result?

Options

  • A97 98 99 100 null null null
  • B97 98 99 100 101 102 103
  • CCompilation rails.
  • DA NullPointerException is thrown at runtime.
  • EAn ArrayIndexOutOfBoundsException is thrown at runtime.

How the community answered

(29 responses)
  • A
    69% (20)
  • B
    3% (1)
  • C
    3% (1)
  • D
    10% (3)
  • E
    14% (4)

Explanation

Option A is correct because the inner loop uses chs.length (which is 2, the number of rows) instead of chs[a].length (the number of columns per row). This means the fill loop only writes to indices 0 and 1 of chs[1], leaving its remaining three elements as null. When the print loop iterates over all five elements of chs[1], Java's string concatenation (c + " ") silently converts null references to the literal string "null", producing 99 100 null null null.

B is wrong because it assumes the inner loop runs up to chs[a].length (5 for row 1), but it runs up to chs.length (2). C is wrong because the code compiles without error - jagged arrays and the loop structure are both valid Java. D is wrong because string concatenation ("" + null) never throws a NullPointerException; it produces "null". E is wrong because the fill loop never exceeds the bounds of either row - chs[0] has 2 slots and chs[1] has 5, and b only reaches 1.

Memory tip: When you see a nested loop over a 2D array, always check which length the inner loop uses - array.length gives row count, while array[i].length gives column count for that row. A mismatch is a classic exam trap for jagged arrays.

Topics

#jagged arrays#nested loops#array initialization#null references

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice