What is Java String charAt() method?
The Java string class charAt() method returns the character at the specified index of a string. This specified index is provided as a parameter and it ranges from 0 to n-1, where n represents the length of the string. Syntax
public char charAt(int index)
Parameters
The charAt() method receives a positive integer because the length is never below 0.
Returns
It always returns a char value of the specified index but if parameter value is negative or above the length of the string then its throws an exception.
Java String charAt() Method Examples
class Main {
public static void main(String[] args) {
String str = "Java charAt() method example";
// picking the A character of the string str at index 9 using charAt() method
System.out.println(str.charAt(9));
// picking the ( character of the string str at index 11 using charAt() method
System.out.println(str.charAt(11));
// picking the ) character of the string str at index 12 using charAt() method
System.out.println(str.charAt(12));
}
}
Output
Handling StringIndexOutOfBoundsException
You’ve already got a handle on using charAt() to retrieve characters from a string, but what if you accidentally use an index that’s out of range? Let’s dive into how to manage the StringIndexOutOfBoundsException in detail, see some examples of handling it with a try-catch block.
Understanding the StringIndexOutOfBoundsException
The StringIndexOutOfBoundsException is thrown when your requested index is either negative or greater than or equal to the length of the string. In other words, if you call charAt() on a string whose length is 5 but you ask for the character at index 10, Java won’t be happy!
So, the key point is to ensure the index you pass to charAt() is between 0 and (string.length() - 1). Otherwise, you’ll trigger this exception and potentially crash your program if you don’t handle it. This is where exception handling comes in.
Using Try-Catch to Handle StringIndexOutOfBoundsException
To demonstrate, let’s see an example where we might run into trouble and how we catch it gracefully:
public class CharAtExceptionExample {
public static void main(String[] args) {
String word = "Hello";
try {
// Intentionally using an invalid index
char letter = word.charAt(10);
System.out.println("Letter at index 10: " + letter);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Oops! " + e.getMessage());
System.out.println("Index is out of range. Let's fix that!");
}
}
}
When we run this, Java immediately complains that index 10 is out of range for "Hello". But thanks to our try-catch, we recover gracefully instead of crashing. In a real application, you might prompt the user for a valid index, or handle it some other way. Either way, you avoid a meltdown by catching the exception.
Counting the Frequency of a Character Using charAt()
Now, let’s see a more practical use case—counting how many times a given character appears in a string. We can do this by iterating over the string and checking each character:
public class CharacterFrequencyExample {
public static void main(String[] args) {
String text = "banana";
char target = 'a';
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == target) {
count++;
}
}
System.out.println("Character '" + target +
"' appears " + count + " times in \"" + text + "\".");
}
}
In this snippet, the loop goes from 0 to text.length() - 1, ensuring our index is always valid. Then we compare each character with our target. If it matches, we increment count. Finally, we print out how many times the character appears. Easy-peasy!
GO TO FULL VERSION