The String.charAt() in Java returns the character at the specified index argument in the given string. Note that String class stores its content in a char array. The charAt() uses the supplied index to get the character from this backing char array.
The charAt() API can be useful when validating the user inputs in specific formats.
1. String.charAt() APIThe charAt() method accepts only one argument of int type that indicates the array index position in the underlying char array. The argument index must be –
Any invalid index argument will result in StringIndexOutOfBoundsException.
2. String.charAt() ExampleIn the following example, we are demonstrating the usage of charAt() method in multiple cases.
Let us start with getting the first character of the string, i.e. the character at the index position 0.
String str = "howtodoinjava.com";
Assertions.assertEquals('h', str.charAt(0));
To get the last character of the String, use the String.length() and subtract 1 to get the last valid index in the string.
Assertions.assertEquals('m', str.charAt(str.length() - 1));
Similarily, we can get a character at any place in the string using its valid index.
Assertions.assertEquals('.', str.charAt(13));
Mentioning again that any invalid index argument will result in StringIndexOutOfBoundsException error.
Assertions.assertThrows(StringIndexOutOfBoundsException.class, ()->{
str.charAt(50);
});
In this Java tutorial, we learned about String‘s charAt() method with examples.
Happy Learning !!
Reference: String class Java Doc
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4