String charAt() method in java

Let’s learn String charAt() method in java.

String charAt() method in java

String charAt() method returns the char value at the specified index. An index ranges from 0 to length() – 1.

The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

If the char value specified by the index is a surrogate, the surrogate value is returned.

Syntax:

public char charAt(int index)

Parameters:

index – the index of the char value.

Returns:

The char value at the specified index of this string. The first char value is at index 0.

Throws:

IndexOutOfBoundsException – if the index argument is negative or not less than the length of this string.

Now let’s see String charAt() method example.

public class StringCharAtMethodJava
{
   public static void main(String[] args)
   {
      String strInput = "HelloWorldJava";
      char ch1 = strInput.charAt(1);
      char ch2 = strInput.charAt(6);
      char ch3 = strInput.charAt(10);
      System.out.println("Character at 1st index is: " + ch1);
      System.out.println("Character at 6th index is: " + ch2);
      System.out.println("Character at 10th index is: " + ch3);
   }
}

Output:

Character at 1st index is: e
Character at 6th index is: o
Character at 10th index is: J


If String index is out of range then we get java.lang.StringIndexOutOfBoundsException. Let’s see an example

class StringCharAtMethodJava 
{
   public static void main(String[] args)
   {
      String strInput = "HelloWorldJava";
      char ch = strInput.charAt(20);
      System.out.println("Character at index 20 : " + ch);
   }
}

Output:

Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 20


Also read – java overview

Reference: oracle docs