String s = \"hello\";
String backup_of_s = s;
s = \"bye\";
At this point, the backup variable still contains the original value \"hello
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.
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";
String str1="this is a string";
String str2=str1.clone();
How about copy like this?
I think to get a new copy is better, so that the data of str1
won't be affected when str2
is reference and modified in futher action.
Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.
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.