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.

  • public char charAt(int indexNumber): Returns a single character available in the string at index number indexNumber. The negative index number or index number beyond the length of the string throws StringIndexOutOfBoundsException.

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
 }
}


charAt() String
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.

1 thought on “charAt() String Example”

Leave a Comment

Your email address will not be published.