title: Java Exception in Counting number of occurrences of character in a string
body: <p>I am a java beginner and want to do some logic stuffs. I have started with a simple program (i.e) to find the total number of occurrences of a character in a string. But i ended up with this exception</p>
  
  <pre><code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 52
      at java.lang.String.charAt(Unknown Source)
  </code></pre>
  
  <p>And i used the following code</p>
  
  <pre><code>public class Main {
  
      public static void main(String[] args) {
          // TODO Auto-generated method stub
          String myStr = "sofdaasdasdaofsdwerwtytuoftyutyusdfsdfsdcsadaswdeasd";
          // Counting number of occurences of 'of' in myStr
          int counter = 0;
          int totalLength = myStr.length();
          char char1;
          char char2;
          // To find of
          String myVal = "of";
          String cmpVal1;
          String cmpVal2;
          String cmpValStr;
          for (int i = 0; i &lt; totalLength; i++) {
              char1 = myStr.charAt(i);
              cmpVal1 = Character.toString(char1);
              char2 = myStr.charAt(i + 1);
              cmpVal2 = Character.toString(char2);
              cmpValStr = cmpVal1 + cmpVal2;
              if (cmpValStr == myVal) {
                  counter++;
              }
  
          }
          System.out.print(counter);
      }
  
  }
  </code></pre>