title: Java += operator on String with charAt() methods results in char addition
body: <p>I'm working through the problems on Codingbat.com and bumped into the fact that for the <code>+=</code> operator, <code>a += b</code> isn't necessarily exactly equal to <code>a = a + b</code>. This is well known and has been discussed on SO before, but I bumped into something strange happening when using the <code>charAt()</code> method combined with the above syntax that I can't make sense of.</p>
  
  <p>Say I have two variables:</p>
  
  <pre><code>String str    = "The";
  String result = "";
  </code></pre>
  
  <p>I want to add the first letter in "str" two times to "result". One way of doing this is to:</p>
  
  <pre><code>result = result + str.charAt(0) + str.charAt(0);
  </code></pre>
  
  <p>which results in <code>result = "TT"</code>.</p>
  
  <p>However, if I use the <code>+=</code> operator, e.g.:</p>
  
  <pre><code>result += str.charAt(0) + str.charAt(0);
  </code></pre>
  
  <p>I get <code>result = "168"</code>. Clearly character addition has taken place (ASCII code for 'T' is 84, 84*2 = 168).</p>
  
  <p>I'm wondering what is actually going on in the first case using the <code>+=</code> operator. According to the <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.26.2" rel="nofollow noreferrer">docs on assignment operators</a>: <code>E1 op= E2</code> is equivalent to <code>E1 = (T)((E1) op (E2))</code>. So I would expect the latter expression to output <code>"168"</code> just like using the <code>+=</code> operator did. But the following outputs <code>"TT"</code> correctly, and not <code>"168"</code>:</p>
  
  <pre><code>result = (String)(result + str.charAt(0) + str.charAt(0));
  </code></pre>
  
  <p>Have I just misunderstood the documentation? I also found an <a href="https://stackoverflow.com/a/693617">answer</a> on SO that suggests that <code>str1 += str2</code> is equivalent to:</p>
  
  <pre><code>str1 = new StringBuilder().append(str1).append(str2).toString();
  </code></pre>
  
  <p>But evaluating the following:</p>
  
  <pre><code>result = new StringBuilder().append(str.charAt(0)).append(str.charAt(0)).toString();
  </code></pre>
  
  <p>Still results in <code>"TT"</code>, not <code>"168"</code>.</p>
  
  <p>Sorry for the long post! I'm just curious at what actually is happening when using <code>charAt()</code> in combination with a String and <code>+=</code>, because the two "equivalents" I've found (if I've translated them from two to three terms correctly) does not produce the same result.</p>