Given the code fragment:
int nums1[] = new int[3];
int nums2[] = {1,2,3,4,5};
nums1 = nums2;
for(int x : nums1){
System.out.print(x + ":");
}
What is the result?
A.
1:2:3:4:5:
B.
1:2:3:
C. Compilation fails.
D. An ArrayoutofBoundsException is thrown at runtime.
题解
程序第 7 行,会将 nums2 的数组对象参考指派给 nums1 保存,因此 nums1 和 nums2 变量所存的对象参考都是一样的,表示为同一个对象。
程序第 8 行,用 foreach 的方式取得 nums1 数组对象的所有元素,并将它们全部印出。
