title: How should I copy Strings in Java?
body: <pre><code>    String s = "hello";
      String backup_of_s = s;
      s = "bye";
  </code></pre>
  
  <p>At this point, the backup variable still contains the original value "hello" (this is because of String's immutability right?).</p>
  
  <p>But is it really <strong>safe</strong> to copy Strings with this method (which is of course not safe to copy regular mutable objects), or is better to write this? :</p>
  
  <pre><code>    String s = "hello";
      String backup_of_s = new String(s);
      s = "bye";
  </code></pre>
  
  <p>In other words, what's the difference (if any) between these two snippets?</p>
  
  <hr>
  
  <p><strong>EDIT - the reason why the first snippet is safe:</strong></p>
  
  <p>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):</p>
  
  <p>Strings are immutable in Java, which means that a String object cannot be modified after its construction.
  Hence,</p>
  
  <p><code>String s = "hello";</code> creates a new String instance and assigns its address to <code>s</code> (<code>s</code> being a reference to the instance/object)</p>
  
  <p><code>String backup_of_s = s;</code> creates a new variable <code>backup_of_s</code> and initializes it so that it references the object currently referenced by <code>s</code>.</p>
  
  <p>Note: String immutability guarantees that this object will not be modified: our backup is safe</p>
  
  <p>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 (<code>backup_of_s</code> in this case)</p>
  
  <p>Finally, <code>s = "bye";</code> creates another String instance (because of immutability, it's the only way), and modifies the <code>s</code> variable so that it now references the new object.</p>