Java String charAt(): Accessing Characters by Zero-Based Index

The String.charAt() method returns the primitive char value located at a specified zero-based index within the string.

Zero-Based Indexing & Traversal: Valid indices range from 0 up to length() - 1. For 32-bit Unicode surrogate pairs, see codePointAt(). To search for a character's index position, see indexOf() and lastIndexOf(). For substring extraction, explore substring(), or loop with for loop.

1. Syntax & Method Signature 🔝

The charAt() method is defined directly in java.lang.String:

 // Formal signature of String.charAt() in java.lang.String
public char charAt(int index)
Parameter / Element Type Description & Operational Rule
index int Zero-based index of the char value to return. Must be in [0 .. length() - 1].
Return Value char The 16-bit UTF-16 character value located at the specified index position.
Exception Runtime Throws StringIndexOutOfBoundsException if index < 0 or index >= length().

2. Basic Index Access: First, Middle, and Last Characters 🔝

Java uses zero-based indexing, meaning the first character is always at index 0 and the last character is at length() - 1:

String my_str = "Welcome to plus2net";

System.out.println("Index 0:  " + my_str.charAt(0));   // W
System.out.println("Index 3:  " + my_str.charAt(3));   // c
System.out.println("Index 15: " + my_str.charAt(15));  // 2
System.out.println("Last:     " + my_str.charAt(my_str.length() - 1));  // t

Terminal Output:

Index 0:  W
Index 3:  c
Index 15: 2
Last:     t

3. StringIndexOutOfBoundsException & Safe Boundary Guards 🔝

Requesting an index outside [0 .. length() - 1] causes a runtime exception. Always guard dynamic index calculations:

String text = "plus2net";

try {
    char ch = text.charAt(text.length());  // index 8 on length 8
} catch (StringIndexOutOfBoundsException e) {
    System.out.println("Caught: " + e.getMessage());
}

 // Safe check
int reqIndex = 10;
if (reqIndex >= 0 && reqIndex < text.length()) {
    System.out.println(text.charAt(reqIndex));
} else {
    System.out.println("Index " + reqIndex + " is out of bounds (valid: 0.." + (text.length() - 1) + ")");
}

Terminal Output:

Caught: Index 8 out of bounds for length 8
Index 10 is out of bounds (valid: 0..7)

4. Forward String Traversal with Loops 🔝

A standard for loop iterates through a string from index 0 up to length() - 1:

String my_str = "plus2net";

for (int i = 0; i < my_str.length(); i++) {
    System.out.println("Index " + i + ": " + my_str.charAt(i));
}

Terminal Output:

Index 0: p
Index 1: l
Index 2: u
Index 3: s
Index 4: 2
Index 5: n
Index 6: e
Index 7: t

5. Reverse Traversal: Printing and Reversing Text 🔝

Starting at length() - 1 and decrementing down to 0 traverses characters in reverse order:

String my_str = "plus2net";

System.out.print("Reversed: ");
for (int i = my_str.length() - 1; i >= 0; i--) {
    System.out.print(my_str.charAt(i));
}
System.out.println();

Terminal Output:

Reversed: ten2sulp

6. charAt() vs. codePointAt(): The Unicode Surrogate Pair Rule 🔝

Java represents strings using UTF-16 code units. Standard characters require 1 unit (16 bits), but emojis require 2 units (a surrogate pair):

Feature str.charAt(index) str.codePointAt(index)
Return Type char (16-bit UTF-16 code unit). int (32-bit Unicode Code Point).
Emoji Handling Returns half of surrogate pair. Returns full 32-bit Unicode integer value.
Primary Use Case Standard ASCII & Latin text processing. Internationalization, emojis, full Unicode.
String word = "Java";
System.out.println("word.charAt(0): " + word.charAt(0));  // J

 // Supplementary Unicode character (Emoji spans 2 code units)
String rocket = "🚀Launch";
System.out.println("Length:              " + rocket.length());        // 8
System.out.println("rocket.charAt(0):    " + (int)rocket.charAt(0));  // 55357
System.out.println("rocket.codePointAt:  " + rocket.codePointAt(0));  // 128640

Terminal Output:

word.charAt(0): J
Length:              8
rocket.charAt(0):    55357
rocket.codePointAt:  128640

7. Production Recipe: Dual-Pointer Palindrome Checker 🔝

Using two index pointers moving toward the center checks palindromes in O(1) extra space without copying or reversing the string:

public class PalindromeChecker {
    public static boolean isPalindrome(String s) {
        if (s == null) return false;
        int left = 0, right = s.length() - 1;

        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println("radar: " + isPalindrome("radar"));  // true
        System.out.println("level: " + isPalindrome("level"));  // true
        System.out.println("java:  " + isPalindrome("java"));   // false
    }
}

Terminal Output:

radar: true
level: true
java:  false

8. Practical Recipe: Character Type Classifier 🔝

Classifying characters into letters, digits, whitespace, and symbols using Character utility methods:

String sample = "User_2026! @Home";
int letters = 0, digits = 0, spaces = 0, others = 0;

for (int i = 0; i < sample.length(); i++) {
    char c = sample.charAt(i);
    if (Character.isLetter(c)) letters++;
    else if (Character.isDigit(c)) digits++;
    else if (Character.isWhitespace(c)) spaces++;
    else others++;
}

System.out.println("Letters: " + letters + ", Digits: " + digits + ", Spaces: " + spaces + ", Others: " + others);

Terminal Output:

Letters: 8, Digits: 4, Spaces: 1, Others: 3

9. Common Developer Pitfalls & Traps 🔝

The Negative Index Trap

Unlike Python where s[-1] returns the last character, Java does not support negative indexing! Calling str.charAt(-1) immediately throws StringIndexOutOfBoundsException. Always use str.charAt(str.length() - 1).

The Off-By-One Index Equals Length Trap

Because strings are 0-indexed, a string of length 5 has valid indices 0, 1, 2, 3, 4. Calling str.charAt(5) fails with an out-of-bounds error. The loop condition must be i < str.length(), never <=.

10. Complete Compilable Java Program 🔝

You can compile and run this complete test class locally in any Java IDE or environment:

public class StringCharAtFullDemo {
    public static void main(String[] args) {
        String test = "plus2net";

        if (test.charAt(0) == 'p') {
            System.out.println("Check 1 Passed: First character is 'p'.");
        }

        if (test.charAt(test.length() - 1) == 't') {
            System.out.println("Check 2 Passed: Last character is 't'.");
        }

        boolean caught = false;
        try {
            test.charAt(-1);
        } catch (StringIndexOutOfBoundsException e) {
            caught = true;
        }
        if (caught) {
            System.out.println("Check 3 Passed: Negative index threw exception.");
        }

        System.out.println("All String.charAt() tests passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: First character is 'p'.
Check 2 Passed: Last character is 't'.
Check 3 Passed: Negative index threw exception.
All String.charAt() tests passed successfully!

11. Frequently Asked Questions (FAQ) 🔝

What is the time complexity of charAt()?

charAt() runs in O(1) constant time because Java strings store characters in an underlying contiguous array with direct index lookups.

What happens when calling charAt() on an empty string?

Since an empty string "" has length 0, calling "".charAt(0) immediately throws StringIndexOutOfBoundsException.

Should I use charAt(i) or substring(i, i+1)?

Always prefer charAt(i) when you only need a single character. It returns a primitive char without allocating a new String object on the heap.

How do I get the numeric digit value of a char?

Use Character.getNumericValue(ch) or subtract '0': int val = str.charAt(i) - '0'.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer