Java String charAt: Syntax, Edge Cases, and Performance
Learn how to use Java's String.charAt() method: syntax, bounds checking, performance, and Unicode limitations.

Working with String.charAt() requires a clear understanding of its syntax, runtime behavior, and practical limits. In Java, String.charAt(int index) returns the char at the specified zero-based position. It is one of the simplest ways to read a single character from a string, but invalid indices and Unicode surrogate pairs often surprise developers. This article explains the method's contract, common pitfalls, and how it compares with alternatives.
The charAt Method and Its Contract
The charAt method is defined on the String class and has the following signature:
public char charAt(int index)It returns the char value at the given index. The index is zero-based, so the first character is at index 0, and the last is at length() - 1. Here is a minimal example:
String greeting = "hello";
char first = greeting.charAt(0); // 'h'
char last = greeting.charAt(4); // 'o'The contract is strict: if index is negative or greater than or equal to length(), charAt throws StringIndexOutOfBoundsException. This exception is a subclass of IndexOutOfBoundsException and is unchecked, so the compiler does not force you to handle it. However, ignoring the possibility in production code can lead to runtime failures.
Handling Index Out of Bounds
Because charAt throws for invalid indices, validate any index that comes from user input, configuration, or other untrusted sources. The explicit check below reports the offending index in a consistent format:
public char safeCharAt(String str, int index) {
if (index < 0 || index >= str.length()) {
throw new IllegalArgumentException("Index out of range: " + index);
}
return str.charAt(index);
}This method checks before calling charAt, so callers receive an IllegalArgumentException with the offending index instead of the default StringIndexOutOfBoundsException. That makes failures easier to diagnose and keeps the validation explicit.
Another common pattern is to use String.length() as the loop bound before calling charAt. For example, iterating over all characters with a traditional for loop:
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// process c
}Because String is immutable, length() stays constant during the loop, so this loop is safe.
Performance and Repeated Access
charAt is O(1) per call. Before Java 9, a String was backed by a char array; with compact strings from Java 9 onward, it is backed by a byte array. In both cases, the method performs a bounds check and reads the relevant value directly. There is no hidden traversal or parsing. In simple loops, the JIT compiler can often inline the method, so the per-call overhead is generally negligible for normal application code.
Because charAt returns a primitive char, it avoids boxing. That makes it a good default for reading characters one at a time, especially in tight loops. In contrast, chars() returns an IntStream, and collecting or converting the values box them into objects, adding allocation pressure in high-throughput text processing.
String is immutable, so the value behind a String cannot change during concurrent access. As with any immutable object, the reference still needs to be safely published before being shared across threads; after that, charAt can be called concurrently without additional synchronization.
Comparing charAt with toCharArray and chars()
toCharArray() copies the entire string into a new char[] array. This is useful when you need random access to many characters or want to modify the array without affecting the original string. However, it creates a copy, which costs memory and time proportional to the string length. For a one-off read, charAt is more efficient.
The chars() method returns an IntStream of the UTF-16 code units. It is convenient for functional-style processing:
str.chars()
.filter(Character::isLetter)
.forEach(c -> System.out.println((char) c));But chars() also incurs stream overhead, and boxing appears when you collect the values. For simple index-based access, charAt is lower-level and more direct.
| Approach | Memory Behavior | Best Use Case |
|---|---|---|
charAt | No copy | Reading a single character or random access |
toCharArray() | Copies the full string | When you need an array to pass to legacy APIs |
chars() | Stream of code units | Functional operations on all characters |
Choose charAt when you know the index and need a direct value. Use toCharArray() only when you need an actual array, and chars() when you are already working with streams.
Unicode Surrogate Pairs and charAt Limitations
A char in Java is a UTF-16 code unit, not necessarily a full Unicode code point. Characters outside the Basic Multilingual Plane (BMP), such as many emojis and some CJK extension characters, are represented as surrogate pairs—two char values. Calling charAt on such a string returns one of the surrogate halves, which is rarely what you want.
For example:
String emoji = "😀";
System.out.println(emoji.length()); // 2
char first = emoji.charAt(0); // high surrogate
char second = emoji.charAt(1); // low surrogateIf you need to work with full Unicode code points, use codePointAt(int index) or iterate with codePoints(). codePointAt returns an int that represents the complete code point, handling surrogate pairs correctly:
int codePoint = emoji.codePointAt(0); // 128512This is especially important when processing user input that may contain non-BMP characters. Relying on charAt for such strings can lead to broken output or incorrect validation.
Practical Example: Validating a String Field
Suppose you need to check whether a string starts with a digit. charAt is concise for this:
public boolean startsWithDigit(String value) {
if (value == null || value.isEmpty()) {
return false;
}
return Character.isDigit(value.charAt(0));
}The code first checks for null and an empty string, then safely accesses the first character. This pattern is common in parsers and input handlers. For other positions, validate the index before calling charAt.
If you need to recognize digits from other scripts, Character.isDigit works for many code points. For non-BMP input, read the code point with codePointAt and pass the resulting int to Character.isDigit(int), because charAt returns only a UTF-16 code unit.
When to Avoid charAt
charAt is not the right tool when you need to modify characters; use a mutable structure such as StringBuilder or char[] instead. It is also not suitable for working with full Unicode code points, because it returns UTF-16 code units; use codePointAt or codePoints() for non-BMP characters. For substring extraction, use substring rather than building the result with repeated charAt calls. Note that substring in modern Java copies the relevant part of the underlying array, so it is not a constant-time operation as it was in older releases.
For simple single-character access, charAt remains the most direct method. Understanding its contract and limitations helps you avoid subtle bugs in production code.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.