First you are assigning the value "hello" (at some place in memory) to test
:
test --------------> "hello"
Then, you are setting myname
to the same location in memory.
test --------------> "hello"
/
myname ----------/
Then, you are assigning the value "how are you?" at a new location in memory to test
:
-> "hello"
/
myname ----------/
test --------------> "how are you?"
It's all about the pointers.
EDIT AFTER COMMENT
I have no idea what the rest of your code looks like, but if you want to be able to update a single String and have the rest of the references to that String update at the same time, then you need to use a StringBuilder
(or StringBuffer
if you need synchronization) instead:
StringBuilder test = new StringBuilder("hello");
StringBuilder myname = test;
StringBuilder foo = test;
StringBuilder bar = test;
test.replace(0, test.length(), "how are you?");
Assert.assertEquals("how are you?", test.toString());
Assert.assertEquals("how are you?", myname.toString());
Assert.assertEquals("how are you?", foo.toString());
Assert.assertEquals("how are you?", bar.toString());
Got it from there?