How should I copy Strings in Java?
String s = "hello";
String backup_of_s = s;
s = "bye";
At this point, the backup variable still contains the original value "hello" (this is because of String's immutability right?).
But is it really safe to copy Strings with this method (which is of course not safe to copy regular mutable objects), or is better to write this? :
String s = "hello";
String backup_of_s = new String(s);
s = "bye";
In other words, what's the difference (if any) between these two snippets?
EDIT - the reason why the first snippet is safe:
Let me just explain things with a little more detail, based on the good answers already provided (which were essentially focused on the question of difference of performance between the 2 snippets):
Strings are immutable in Java, which means that a String object cannot be modified after its construction. Hence,
String s = "hello";
creates a new String instance and assigns its address to s
(s
being a reference to the instance/object)
String backup_of_s = s;
creates a new variable backup_of_s
and initializes it so that it references the object currently referenced by s
.
Note: String immutability guarantees that this object will not be modified: our backup is safe
Note 2: Java garbage collection mechanism guarantees that this object will not be destroyed as long as it is referenced by at least one variable (backup_of_s
in this case)
Finally, s = "bye";
creates another String instance (because of immutability, it's the only way), and modifies the s
variable so that it now references the new object.
Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).
With this in mind, the first version should be preferred.
Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...
So you can copy as in your first example without any problem :
String s = "hello";
String backup_of_s = s;
s = "bye";
Your second version is less efficient because it creates an extra string object when there is simply no need to do so.
Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.