Java String charAt()

The String.charAt() in Java returns the character at the specified index argument in the given string. Note that String class stores its content in a char array. The charAt() uses the supplied index to get the character from this backing char array.

The charAt() API can be useful when validating the user inputs in specific formats.

1. String.charAt() API

The charAt() method accepts only one argument of int type that indicates the array index position in the underlying char array. The argument index must be –

  • Equal to or greater than 0 (Zero)
  • Less than the length of the string i.e. String.length()

Any invalid index argument will result in StringIndexOutOfBoundsException.

2. String.charAt() Example

In the following example, we are demonstrating the usage of charAt() method in multiple cases.

Let us start with getting the first character of the string, i.e. the character at the index position 0.

String str = "howtodoinjava.com";

Assertions.assertEquals('h', str.charAt(0));

To get the last character of the String, use the String.length() and subtract 1 to get the last valid index in the string.

Assertions.assertEquals('m', str.charAt(str.length() - 1));

Similarily, we can get a character at any place in the string using its valid index.

Assertions.assertEquals('.', str.charAt(13));

Mentioning again that any invalid index argument will result in StringIndexOutOfBoundsException error.

Assertions.assertThrows(StringIndexOutOfBoundsException.class, ()->{
    str.charAt(50);
});

In this Java tutorial, we learned about String‘s charAt() method with examples.

Happy Learning !!

Reference: String class Java Doc

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial