More on String Methods
Learn about some built-in functions allowed on strings.
Finding a character at an index
Java provides the charAt()
method, which when called on a string, returns the character at the specified index.
For example, if the string is “Java” and the index is , then ‘v’ will be returned. Below is a demonstration.
Let’s run a simple example.
Press + to interact
class CharacterAtIndex{public static void main(String args[]){String s1 = "Java";System.out.println(s1.charAt(2)); // Character at index 2System.out.println(s1.charAt(4)); // ❌ Error: Character at index 4}}
Look at line 6. We are obtaining the character of the string s1
at the 2nd index. It returns v as a result.
At line 7, we are obtaining the character of the string s1
at 4th index. It will give this error: ...