Java String charAt() Method Examples

Java String charAt() method returns the character at the specified index.


Java String charAt() Example

Let’s look at a simple example of charAt() method. We will use JShell to run the code snippet.

jshell> String s1 = "abcd";
s1 ==> "abcd"

jshell> System.out.println("Character at index 1 = " + s1.charAt(1));
Character at index 1 = b
Java String CharAt Example
Java String charAt() Example

What if String is defined with Unicode Characters?

We can declare string variable using Unicode too. In this case, the Unicode value is converted to the character and then the character is returned. Let’s look at a simple example.

jshell> String s2 = "A\u0066\u0070B";
s2 ==> "AfpB"

jshell> System.out.println("Character at index 1 = " + s2.charAt(1));
Character at index 1 = f

What if the charAt() Method Argument is Invalid?

The valid value for the charAt() method is from 0 to the string length -1. If the argument is invalid, java.lang.StringIndexOutOfBoundsException is thrown. Let’s look at a simple example for this.

jshell> String s1 = "Java";
s1 ==> "Java"

jshell> s1.charAt(-5);
|  Exception java.lang.StringIndexOutOfBoundsException: String index out of range: -5
|        at StringLatin1.charAt (StringLatin1.java:47)
|        at String.charAt (String.java:702)
|        at (#45:1)

jshell> s1.charAt(100);
|  Exception java.lang.StringIndexOutOfBoundsException: String index out of range: 100
|        at StringLatin1.charAt (StringLatin1.java:47)
|        at String.charAt (String.java:702)
|        at (#46:1)

jshell>

Conclusion

  • Java String charAt() method returns the character at the specified index.
  • The method throws StringIndexOutOfBoundsException for invalid index value.
  • This method is declared in the CharSequence interface and implemented in the String class.