1Z0-808 · Question #33
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?
The correct answer is A. 1:2:3:4:5. In Java, arrays are reference types, so nums1 = nums2 does not copy the array contents - it reassigns nums1 to point to the same 5-element array object that nums2 references. After that assignment, nums1 has length 5, so the enhanced for loop iterates all five elements…
Question
Options
- A1:2:3:4:5:
- B1:2:3:
- CCompilation fails.
- DAn ArrayIndexOutOfBoundsException is thrown at runtime.
How the community answered
(32 responses)- A75% (24)
- B16% (5)
- C6% (2)
- D3% (1)
Explanation
In Java, arrays are reference types, so nums1 = nums2 does not copy the array contents - it reassigns nums1 to point to the same 5-element array object that nums2 references. After that assignment, nums1 has length 5, so the enhanced for loop iterates all five elements, printing 1:2:3:4:5:, making A correct.
B is wrong because the original size of nums1 (3) is irrelevant after reassignment - the reference now points to a length-5 array, not a length-3 one. C is wrong because Java allows arrays of different sizes to be assigned to the same reference variable, so this compiles fine. D is wrong because no index-based access occurs here; the enhanced for loop uses the actual length of the array being iterated, which is now 5 - no out-of-bounds condition exists.
Memory tip: Think of an array variable as a remote control, not the TV itself. Reassigning the variable just points the remote at a different TV - the new TV's size (length) is what matters going forward.
Topics
Community Discussion
No community discussion yet for this question.