Hit enter after type your search item

What is Java charAt method?

The charAt(int) method returns the character in the specified string for a given index number. The index of string starts at zero.

For example, consider this string:

“Hello World Java”

You want to know the character at 6th index position in that string by using charAt method.

Syntax of using charAt Java method

public char charAt(int index)

A few points about the string charAt method:

  • The charAt takes an argument which is an int type.
  • The method returns the character as char for the given int argument. The int value specifies the index that starts at 0.
  • The index range must be between 0 to the length of string -1.
  • If the index value is greater than string length or a negative number, an error IndexOutOfBoundsException occurs.
  • The charAt method is specified by CharSequence.

The example of using charAt method

In the following example, Java charAt method is used to return the character in a string. I will use the same string as in introductory section. Let us see which characters occur at the index 6 and 12:

The output:

Java charAt string

A program to tell if certain characters exist in a string?

By using charAt method, this program will output if a vowel character occurs at the start of the specified string. For that, a string is entered by the user and program will check for these characters. For taking the user input, the Scanner class is used:

See the output of the tried strings:

What if given index is greater than the length of string?

As mentioned earlier, if you provide a negative number or greater than the string length then an error occurs:

charAt string error

You saw, for the index 15, the program generated StringIndexOutOfBoundsException error with the description: String index out of range: 15.

The indexOf method

The indexOf method returns the index number of the given character in the specified string. For example, if we have a string:

“indexOf method in Java”

This is how you may use the indexOf method for getting ‘J’ index number:

x = str.indexOf(‘J’);

The example program:

The output:

The indexOf ‘J’ is: 18

Learn more about indexOf method with details – Java indexOf method

This div height required for enabling the sticky sidebar