title: Best way to modify an existing string? StringBuilder or convert to char array and back to string?
body: <p>I'm learning Java and am wondering what's the best way to modify strings here (both for performance and to learn the preferred method in Java). Assume you're looping through a string and checking each character/performing some action on that index in the string.</p>
  
  <p>Do I use the <code>StringBuilder</code> class, or convert the string into a char array, make my modifications, and then convert the char array back to a string?</p>
  
  <p>Example for <code>StringBuilder</code>:</p>
  
  <pre><code>StringBuilder newString = new StringBuilder(oldString);
  for (int i = 0; i &lt; oldString.length() ; i++) {
      newString.setCharAt(i, 'X');    
  }
  </code></pre>
  
  <p>Example for char array conversion:</p>
  
  <pre><code>char[] newStringArray = oldString.toCharArray();
  for (int i = 0; i &lt; oldString.length() ; i++) {
      myNameChars[i] = 'X';    
  }    
  myString = String.valueOf(newStringArray);
  </code></pre>
  
  <p>What are the pros/cons to each different way? </p>
  
  <p>I take it that <code>StringBuilder</code> is going to be more efficient since the converting to a char array makes copies of the array each time you update an index.</p>