user3078643 user3078643 - 1 month ago 6x
Java Question

Why don't two variables referencing the same object change when one of them does?


The below code show that when affecting an array to an another one, the two arrays becomes depending to each others.

int tab [] = {1,2,3};

int tab2 [] = tab;

tab2[0] = 5;

System.out.print(tab[0]); // 5

I want to know why this isn't the same with the type
, since if we had the following :

String ch1 = "hello";

String ch2 = ch1;

ch2 = "hi";

System.out.print(ch1); // hello

The two variables
are referencing the same string, so changing one will affect the other.


Think like this.

Both array and String operate based on Addresses.

When you say arr1 = arr2, you are telling that arr1 is going to be pointing to same address location as arr2.

With strings, "XYZ" is also a string, which contains an address location. when you say str1 = str2, str1 will be pointing to same address as str2. But when you say str1 = "XYZ", "XYZ" is another object which is stored at a different address. So, str1 will be reassigned to the new address.

Even with arrays, if you say arr1 = arr3, arr2 won't be changing. arr1 will be repointed to a new address pointed by arr3. But when you say arr1[0], you are actually trying to change the value stored in location, so it will also influence arr2 or arr3 depending on which assignment is latest.