Given:
public class Test {
public static void main(String[] args) {
int numbers[];
numbers = new int[2];
numbers[0] = 10;
numbers[1] = 20;
numbers = new int[4];
numbers[2] = 30;
numbers[3] = 40;
for(int x : numbers){
System.out.print(" " + x);
}
}
}
What is the result?
A.
10 20 30 40
B.
0 0 30 40
C. Compilation fails
D. An exception is thrown at runtime
题解
程序第 9 行,将新长度为 4 的整数数组指派给 numbers 变量,因此在这之前长度为 2 的整数数组没有被任何的变量所指向(此数组空间可称为孤岛),其所占用的内存会自动在稍后被 Java 的垃圾回收(Garbage Collection)机制给回收重新使用。
数值数组里的数值,一开始的初始值为 0。程序只有在第 10~11 行时更改了 numbers 数组对象索引 2 和 3 的值。因此最后输出为「 0 0 30 40」。
