title: String index out of range: -2
body: <p>For the following program am getting exception:</p>
  
  <pre><code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
      at java.lang.String.substring(String.java:1911)
      at Names.main(Names.java:33)
  </code></pre>
  
  <p>for line </p>
  
  <pre><code>System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
  </code></pre>
  
  <p>Do you see any problem in this line?</p>
  
  <pre><code>/* Names.java */
  
  import java.io.*;
  
  public class Names {
  
  /** Performs various string operations on the name John Fitzgerald kennedy.
   *     
   * @param arg is not used
   */
  
      public static void main(String[] args) {
          String first = "john";
          String middle = "Fitzgerald";
          String last = "Kennedy";
          String initials;
          String firstInit, middleInit, lastInit;
  
          firstInit = first.substring(0, 1);
          middleInit = middle.substring(0,1);
          lastInit = last.substring(0,1);
          initials = firstInit.concat(middleInit);
          initials = initials.concat(lastInit);
  
          System.out.println();
          System.out.println(first+" "+middle+" "+last+" ");
          System.out.println(initials);
          System.out.println(last+", "+first+" "+middle);
          System.out.println(last+", "+first+" "+middleInit+".");
          System.out.println(first.toUpperCase()+" "+last.toUpperCase());
  
          System.out.println(first+" equals john is "+first.equals("john"));
          System.out.println(first+" equals john (ignoring case is) "+first.equalsIgnoreCase("john"));
          System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
          System.out.println("The index of \"gerald\" within "+middle+" is "+middle.indexOf("gerald"));
          System.out.println("The index of \"gerald\" within "+last+" is "+last.indexOf("gerald"));
  
          System.out.println();
      }
  
  }
  </code></pre>