1Z0-808 · Question #86
Given: class X { static void m (int[] i) { i[0] += 7; } public static void main (String[] args) { int[] j = new int[1]; j[0] = 12; m(j); System.out.println(j[0]); } } What is the result?
The correct answer is C. 19. C is correct because Java arrays are objects passed by reference - when j is passed to m(), both i and j point to the same array in memory. So i[0] += 7 modifies the original array: 12 + 7 = 19. A (7) is wrong - the method adds 7 to the existing value, it doesn't replace it. B…
Question
Options
- A7
- B12
- C19
- DCompilation fails.
- EAn exception is thrown at runtime.
How the community answered
(33 responses)- A3% (1)
- B3% (1)
- C73% (24)
- D15% (5)
- E6% (2)
Explanation
C is correct because Java arrays are objects passed by reference - when j is passed to m(), both i and j point to the same array in memory. So i[0] += 7 modifies the original array: 12 + 7 = 19.
- A (7) is wrong - the method adds 7 to the existing value, it doesn't replace it.
- B (12) would be correct only if Java passed arrays by value (copying them), but it doesn't - the array reference is shared.
- D (Compilation fails) is wrong - the code is syntactically valid Java.
- E (Runtime exception) is wrong -
jis a properly initialized array of length 1, soi[0]is a valid index.
Memory tip: Think of an array variable as a TV remote - passing it to a method gives that method its own copy of the remote, but both remotes still control the same TV. Changes to the TV (array contents) are visible everywhere.
Topics
Community Discussion
No community discussion yet for this question.