title: Java - String Index Out of Bounds Exception
body: <p>I'm getting the following exception on the line where head is assigned and I'm not sure why:</p>
  
  <p><code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 44</code></p>
  
  <p>When using "{1,2},3" as the value of <code>s</code>, running a debugger I can follow the loop and it is correctly assigning <code>commaSpot</code> to be 5 as I think it should. But for some reason <code>s.charAt(commaSpot))</code> doesn't think 5 is a valid index even though s is 7 characters long.</p>
  
  <pre><code>int commaSpot = 0;
  int bracePairs = 0;
  for(int i = 0; i &lt; s.length(); i++) {
     if(s.charAt(i) == '{') bracePairs++;
     if(s.charAt(i) == '}') bracePairs--;
     if(s.charAt(i) == ',' &amp;&amp; bracePairs == 0) {
        commaSpot = i;
        break;
     }
  }
  head = s.substring(0, s.charAt(commaSpot));
  tail = s.substring(s.charAt(commaSpot), s.length());
  </code></pre>