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。
