Example of Java String charAt()
Example 1:
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 CodeOutput:
C
N
Let's look at using the charAt() function with a higher index value. At runtime, it throws a StringIndexOutOfBoundsException in this situation.
Example 2:
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 CodeOutput:
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)
Frequently Asked Questions
How to use char() in Java?
Java does not have a char() method. Instead, use the char data type directly or access characters using the charAt() method.
What is the return type of charAt?
The return type of the charAt() method in Java is char, which represents a single 16-bit Unicode character from the string.
How to check each character in a string in Java?
Use a for loop with the charAt() method to access and check each character in the string one by one.
Example:
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// check c
}
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
The charAt() method in Java is a simple yet powerful tool for accessing individual characters in a string based on their index. It is widely used in string manipulation, validation, and character-based operations. Understanding how to use charAt() effectively helps in writing efficient code for tasks like iteration, comparison, and searching within strings.
Recommended Readings: