1

Question

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 String, since if we had the following :

String ch1 = "hello";

String ch2 = ch1;

ch2 = "hi";

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

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user3078643
  • 129
  • 1
  • 9

3 Answers3

3

When you use

int tab2 [] = tab;

then tab2 is a reference to the same array. Changing the value of tab2[0] meaning you change a value inside the data structure that both tab and tab2 are pointing at.

Using

ch2 = "hi";

create a new instance of String, it does not change the object that ch2 was referring to before.

f1sh
  • 11,489
  • 3
  • 25
  • 51
3

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.

Buddha
  • 4,339
  • 2
  • 27
  • 51
2

You aren't changing the String itself, you are just setting another value for ch2 reference, so it refers to a new String object, ch1 still refers to the old String object.

To make your array code similar to the string code, you need to change it a bit

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

int tab2 [] = tab;

tab2 = new int[]{5,6,7};

System.out.print(tab[0]); // 1
puhlen
  • 8,400
  • 1
  • 16
  • 31