Example
The charAt() function returns the character in a string at the given index. The first character has an index of 0, and the second has an index of 1, and so on.
Program:
public class Stringoperation4
{
public static void main(String args[])
{
String str="CodingNinjas";
System.out.println(str.charAt(0));//C
System.out.println(str.charAt(6));//N
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
C
N

You can also try this code with Online Java Compiler
Run Code
Let's look at using the charAt() function with a higher index value. At runtime, it throws a StringIndexOutOfBoundsException in this situation.
Program:
public class charExample{
public static void main(String args[]){
String str="codingninjas";
char ch=str.charAt(20);//returns char at the 10th index
System.out.println(ch);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 20
at java.lang.String.charAt(String.java:658)
at charExample.main(charExample.java:4)

You can also try this code with Online Java Compiler
Run Code
Frequently Asked Questions
What is a string class in Java?
The java.lang.String class in Java has a multitude of built-in methods for manipulating strings. We may execute actions on String objects using these methods, such as cutting, concatenating, converting, comparing, and replacing strings.
What do you mean by strings being immutable?
String objects are immutable in Java, meaning they can't be updated or modified. A string object's data or state cannot be changed after being created.
Which type of indexing is used in the charAt() method?
0-based indexing is used while using the charAt() method. The first character has an index of 0; the second has an index of 1, and so on.
Conclusion
In this article, we have extensively discussed the string class method charAt() of the java programming language with various examples.
We hope this blog has helped you enhance your charAt() method knowledge. If you would like to learn more, check out our articles on Understanding Strings, Strings Operations, and String Interview Questions In Java.
Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problems, Interview experience, Coding interview questions, and the Ultimate guide path for interviews.
Do upvote our blog to help other ninjas grow. Happy Coding!