This statement:
s2 = s1;
copies the value of s1 to s2 . This value is just a reference, so now s1 and s2 refer to the same object. Therefore, if it was a mutable type (e.g. StringBuilder or ArrayList ), then you will be right to be concerned.
However, String is immutable. You cannot change the object to change its text data, so just copy the link. Changing the s2 value to link to another line (or creating a null link) will not change the s1 value:
String s1 = "hello"; String s2 = s1; s1 = "Something else"; System.out.println(s2);
If you really want to create a new String object, you can use the constructor that you already (unnecessarily) use for s1 :
s2 = new String(s1);
However, this is very rarely a good idea.
Jon skeet
source share