title: java.lang.StringIndexOutOfBoundsException: String index out of range: 4
body: <p>I have been trying to write a Java program which converts the first letter of every word of a string into a capital letter. Right now it looks like this:</p>
  
  <pre><code>package strings;
  import java.util.Scanner;
  
  public class small_cap {
      public static void main(String[] args) {
  
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter the sentence");
          String st = sc.next();
          String str = " " + st;
  
          int j = 0; char chr = ' ';
  
          for (int i = 0; i &lt; str.length(); i++){
              j = i + 1;
              chr = str.charAt(j);
              if (chr == ' '){
                  char a = Character.toUpperCase(str.charAt(j));
                  str = str.replace(str.charAt(j), a);
              }
              else{
                  char a = Character.toLowerCase(str.charAt(j));
                  str = str.replace(str.charAt(j), a);
              }
          }
          System.out.println(str);
      }
  }
  </code></pre>
  
  <p>Unfortunately I keep on getting the error:</p>
  
  <pre><code>java.lang.StringIndexOutOfBoundsException: String index out of range: 4
      at java.lang.String.charAt(String.java:658)
      at small_cap.main(small_cap.java:19)
  </code></pre>
  
  <p>I don't really see any fault in the code. Can someone please point out where I am going wrong?</p>