Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: From a computational perspective, what happens if you set an array as a reference to another array?

int [] arr1 = new int[]{4,6,3,2,7,8};
int [] arr2 = new int[]{6,7,5,3,2,9};
arr2 = arr1;
System.out.println(arr2[3]);  // 2   ( =arr1[3] )

The output of this code is 2.

  • So what's exactly happening here?

  • Is it that arr1 and arr2 are in different memory locations but arr2 is pointing at the values of arr1?

  • What happened to the original values of arr2?

  • Are they still accessible or were they removed by garbage collection?

  • if they are accessible, does the programmer have to free the memory of the 2nd array?

like image 814
TheSaviour Avatar asked Dec 06 '25 09:12

TheSaviour


1 Answers

arr1 and arr2 are both references.

Initially they refer to different arrays.

When you write arr2 = arr1;, nothing is referring to the second array in your program and so it is indeed eligible for garbage collection.

like image 82
Bathsheba Avatar answered Dec 07 '25 22:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!