English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String charAt() method returns the character at the specified index.
The syntax of the string.charAt() method is:
string.charAt(int index)
index - Character index (integer value)
Return the character at the specified index (index).
Note:If the index passed to charAt() is negative or out of range, an exception will be thrown.
class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "Learn\nJava"; //first character System.out.println(str1).charAt(0)); // 'L' //seventh character System.out.println(str1.charAt(6)); // 'J' //sixth character System.out.println(str2.charAt(5)); // '\n' } }
In Java, the index of a string starts from 0, not1. This is why charAt(0) returns the first character. Similarly, charAt(5) and charAt(6) to return the sixth and seventh characters.
If you need to find the index of the first occurrence of a specified character, please useJava String indexOf()Methods.