What does the method print
# Topic
Arrays as parameters
# Problem
What does the method print
Here is a method that takes an array:
public static void method(int[] array) {
array = new int[] { 1, 2, 3 };
}
2
3
We invoke this method inside another one:
int[] numbers = { 4, 5, 6 };
method(numbers);
System.out.println(Arrays.toString(numbers));
2
3
4
5
6
7
What does this code print to the standard output?
Select one option from the list
[x] [4, 5, 6]
[ ] The code can't be compiled.
[ ] [ ]
[ ] [1, 2, 3, 4, 5, 6]
[ ] It throws an exception.
[ ] [1, 2, 3]
2
3
4
5
6
Correct.
The correct answer is [4, 5, 6]
.
Practice makes perfect. Good for you for not giving up easily!
# Hint & Explain
We pass the reference of 'numbers' to the method. Let's say it's XYZ999. The variable 'array' within the method get's a copy of it. So before any statement within the method is executed, we have 'numbers' with reference XYZ999 and 'array' (in scope of the method) with reference XYZ999. XYZ999 points to the place, where the actual values (4, 5, 6) are saved.
Then we instance 'array' with "array = new int[] { 1, 2, 3 }". With that, 'array' get's a new reference because we do instance it. Let's say ABC888. We have now 'array' with reference ABC888 which point to the place, where the actual values (1, 2, 3) are saved.
AND we still have 'numbers' with reference XYZ999 which points to (4, 5, 6). That's why printing 'numbers' print .....