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?
A.
97 98
99 100 null null null
99 100 null null null
B.
91 98
99 100 101 102 103
99 100 101 102 103
C. Compilation fails.
D. A NullPointerException is thrown at runtime.
E. An ArraylndexOutOfBoundsException is thrown at runtime.
題解
第10行的for迴圈一開始,a = 0, b = 0,所以chs[0][0] = "97"。
接下來,a = 0, b = 1,所以chs[0][1] = "98"。
然後,a = 1, b = 0,所以chs[1][0] = "99"。
最後,a = 1, b = 1,所以chs[1][1] = "100",跳出迴圈。
其他沒設定到的陣列元素,初始值為null。