String se = new String("Hello world");
Now we have a variable se
, which points to a string "Hello world"
. Simple enough.
String sx = se;
Now we have a variable sx
and a variable se
, which both point to "Hello world"
. In this case, they point to the exact same string object, but generally speaking in Java we don't like to care about that; the JVM does just fine managing string objects without us having to think about it.
sx = "Hello aliens";
Now we've changed what the variable sx
points to. We haven't said anything at all about se
. So sx
points to "Hello aliens"
and se
to "Hello world"
, since we haven't changed anything on the se
side.
If you're trying to understand reference semantics, strings are a bad example, since they're immutable in Java. Consider making a simple class like the following.
public class MyContainer {
public int value;
public MyContainer(int value) {
this.value = value;
}
}
Then make a few instances of MyContainer
and do basically what you did with the strings with it. If two variables point to the same MyContainer
and you change value
on one, it'll be reflected in the other, but not if you change where the variable points.
MyContainer a = new MyContainer(0);
MyContainer b = a;
// a.value and b.value are both 0 here.
a.value = 99;
// a.value and b.value are both 99 here.
b = new MyContainer(100);
// a.value is still 99; we only changed b here.