1Z0-803 · Question #102
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. When an array is passed as an argument to a method, a copy of the reference to that array is passed, allowing modifications to the array's elements within the method to directly affect the original array object.
Question
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?
Options
- A7
- B12
- C19
- DCompilation fails.
- EAn exception is thrown at runtime.
How the community answered
(17 responses)- A6% (1)
- B12% (2)
- C71% (12)
- E12% (2)
Why each option
When an array is passed as an argument to a method, a copy of the reference to that array is passed, allowing modifications to the array's elements within the method to directly affect the original array object.
The value 7 is added to the existing array element, not set as the new value of the element.
The array element is modified within the `m` method, so its value is no longer 12 when printed.
The array `j` is initialized with `j[0] = 12`. When `m(j)` is called, the array reference is passed by value, meaning both `j` and the method parameter `i` refer to the same array object in memory. Inside `m`, `i[0] += 7` modifies the shared array object, changing `j[0]` from 12 to 19. Therefore, `System.out.println(j[0])` outputs 19.
The provided code is syntactically correct and will compile without any errors.
There are no operations in the code that would lead to a runtime exception, such as an `ArrayIndexOutOfBoundsException` or `NullPointerException`.
Concept tested: Array reference passing and modification in methods
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Topics
Community Discussion
No community discussion yet for this question.