I have been doing questions in my programming book and came across this question:
What is the output of the following code?
int[][] array = new int[5][6];
int[] x = {1, 2};
array[0] = x;
System.out.println("array[0][1] is " + array[0][1]);
The book says the answer is:
array[0][1] is 2
I learned so far that resizing an array isn't possible. From what I understand of this problem is that
int[][] array = new int[5][6]
is creating 5 arrays of 6 elements which would display 0's by default if you displayed it on the console
000000
000000
000000
000000
000000
and now from what I understand is that
array[0] = x;
is basically resizing the first array which has six elements of 0 into an array with 2 elements: 1 and 2.
What am I not understanding? Is it that
array[0] = x;
is making it so it's actually just changing the index 0 element and index 1 element of the first array? and keeping index 2,3,4,5 elements as 0's in array[0]?
I found this question Resize an Array while keeping current elements in Java? but I don't think it helps me answer this question.
This line
array[0] = x;
is not resizing the array array[0]
; it's replacing the array array[0]
such that array
is now
12
000000
000000
000000
000000
The old array[0]
is now discarded and it will be garbage collected. Now array[0]
and x
refer to the same array object, {1, 2}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With