Friday, 23 December 2016

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.


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...