Java String charAt() method example

The method java.lang.String.charAt(int index) returns the character at the specified index argument in the String object.

As we know, Java string is internally stored in char array. This method simply use the index to get the character from that backing char array in string object.

1. charAt() method argument

The only method argument is index. It must be on int type. The argument index must be –

  1. Equal to to greater than ‘0’
  2. Less than length of string characters i.e. str.length()-1

Any invalid index argument will result in StringIndexOutOfBoundsException.

2. Java String charAt() method example

Let’s learn to use String.charAt() method with an realtime example.

public class StringExample 
    public static void main(String[] args) throws Exception 
        String blogName = "";
        char c1 = blogName.charAt(0);   //first character
        char c2 = blogName.charAt(blogName.length() - 1);   //last character
        char c3 = blogName.charAt( 5 );        //random character
        System.out.println("Character at 0 index is: "+c1);
        System.out.println("Character at last is: "+c2);
        System.out.println("Character at 5 index is: "+c3);
        char c4 =  blogName.charAt( 50 );        //invalid index

Program output:

Character at 0 index is: h
Character at last is: m
Character at 5 index is: d

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
	String index out of range: 50
	at java.lang.String.charAt(
	at com.howtodoinjava.demo.StringExample.main(

In this example, we learned about String class’s charAt() method with an example.

Happy Learning !!


String class Java Doc

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.