title: How to prevent an ArrayIndexOutOfBoundsException in this case?
body: <p>The question is:
  given a string: aaaBBB</p>
  <p>I need to print: a3B3
  (counting occurrences of each letter in a given string).</p>
  <p>I tried the following:</p>
  <pre><code>        String x = &quot;aaaBBB&quot;;
          char[] c = x.toCharArray();
          StringBuilder sb = new StringBuilder();
  
          int count = 1;
          System.out.println(c.length);
          
          for (int i = 0; i &lt; c.length; i++) {
                  if (c[i] == c[i+1]) {
                      count++;
                  } else {
                      sb.append(c[i]).append(count);
                      count = 1;
                  }
          }
          System.out.println(sb);
  </code></pre>
  <p>I'm getting an ArrayIndexOutOfBounds Exception, for my last iteration, when I check c[i] with c[i+1] (pretty obvious, because the index i+1 doesn't exist).</p>
  <p>I'd want to know some ways to avoid getting this exception, without changing the if condition.
  Might sound like poor research, but I've been trying this for quite some time now, but not able to get through, before posting it here.</p>