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


Also read – java overview

Reference: oracle docs