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
- Equal to to greater than ‘0’
- 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 = "howtodoinjava.com"; 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(String.java:658) at com.howtodoinjava.demo.StringExample.main(StringExample.java:17)
In this example, we learned about String class’s charAt() method with an example.
Happy Learning !!
Reference: