Two java variables referencing same string object don't sync

From my novice perspective of Java object, if two variables referencing one object, updating one variable should do the same to the other, as the code shows below:

SomeObject s1 = new SomeObject("first");
SomeObject s2 = s1;
s2.setText("second");
System.out.println(s1.getText()); // print second
System.out.println(s2.getText()); // print second as well

I referenced the code from this thread.

However, this doesn't apply to String class. See code below:

String s_1 = new String("first");
String s_2 = s_1;
s_2 = "second";
System.out.println("s_1: " + s_1 + " s_2:  " + s_2); 
//s_1 appears to be "first" and s_2 "second"

Is this because the difference between String class and self-declared class? Thank you for your help!

Jon Skeet
people
quotationmark

No, the difference is in the kind of change you make.

This code:

s2.setText("second")

doesn't change the value of either s2 or s1. Both s1 and s2 refer to the same object as they did before... but the contents of the object has changed.

Compare that with this code:

s_2 = "second";

Here you're changing the value of s2 to be a reference to a different object. Changing the value of s_2 doesn't change the value of s_1 at all - it still refers to the same object that it did before.

You probably want to read up on the differences between variables, objects and references - once you can get that clear in your head, everything else will make a lot more sense.

people

See more on this question at Stackoverflow