Way2Java

charAt() String Example

Many methods exist in java.lang.String class used for different string manipulations like checking the availability of a character, to extract a part of a string or to convert a data type to string etc. The present method is charAt() String.

charAt(int index) extracts a single character from a string.

Following is the method signature of charAt() String.

Following example illustrates the usage of all the 9 overloaded methods.

public class StringMethodDemo
{
  public static void main(String args[])
  {
   String str = "ABCDEF";
   
   char ch1 = str.charAt(1);
   
   System.out.println("Character at 1 index: " + ch1);
   System.out.println("Character at 4 index: " + str.charAt(4));

   System.out.println("\nPrinting all characters in a for loop");
   for(int i = 0; i < str.length(); i++)
   {
     System.out.println(str.charAt(i));
   }

   System.out.println(str.charAt(10));  // this throws exception, see screenshot
 }
}



Output screenshot on charAt() String Example

System.out.println(str.charAt(10));

The above statement throws StringIndexOutOfBoundsException (see screenshot) as charAt(10) crosses the length of the string. There is no 10th character in the stirng str. The length itself is 6 characters. Even negative index like str.charAt(-4) throws the same StringIndexOutOfBoundsException.