Java StringBuilder charAt() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition

In Java, sb.charAt(index) reads and returns the single char at zero-based position index inside a StringBuilder. Unlike mutating methods, it leaves the builder's contents and length untouched.

It works well for inspecting characters while building text—for example checking the last character before adding or trimming punctuation, or scanning a dynamic buffer without calling toString() first.

An instance method of the java.lang.StringBuilder class (since Java 1.5, JDK 1.5): a final, mutable sequence of UTF-16 characters that is not thread-safe. Call it on an existing builder, as in sb.charAt(...). No import is needed because java.lang is always visible.

Syntax

Pass an index from 0 up to sb.length() - 1.

Java
StringBuilder sb = new StringBuilder("Java");
char first = sb.charAt(0);                  // 'J'
char last  = sb.charAt(sb.length() - 1);    // 'a'
CallWhat it does
sb.charAt(0)Reads the first char in the builder.
sb.charAt(sb.length() - 1)Reads the trailing char (when length() > 0).
sb.setCharAt(i, ch)Counterpart that writes a char at index i.

charAt() returns a single 16-bit UTF-16 code unit. For supplementary characters such as emoji, call codePointAt() instead.

Library declarations
Java
// java.lang.StringBuilder
public char charAt(int index)

Parameters

ParameterDescription
index (int)Zero-based position to read (0 <= index < length()).

Return Value

Return ValueDescription
charThe UTF-16 char stored at index.

Compare with Similar Methods

Reading and updating characters in a StringBuilder:

MethodHow it differs
setCharAt(index, ch)Overwrites the char at index in place (returns void).
codePointAt(index)Returns the full Unicode code point (handling surrogate pairs).
String.charAt(index)Same lookup on an immutable String.
substring(start, end)Extracts a range as a String rather than one char.

Java Examples

Example 1 — Inspect First and Last Characters Across Edits

Check how charAt() reflects in-place builder mutations immediately without converting to a String.

Java
public class StringBuilderCharAtEdits {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Build");
        System.out.println("Before: first=" + sb.charAt(0) + ", last=" + sb.charAt(sb.length() - 1));

        sb.append("er!");
        sb.setCharAt(0, 'b');
        System.out.println("After:  first=" + sb.charAt(0) + ", last=" + sb.charAt(sb.length() - 1));
    }
}

How It Works

  1. Read initial ends. On "Build" (length 5), index 0 is 'B' and index 4 is 'd'.
  2. Mutate buffer in place. Appending "er!" and changing index 0 updates the same object.
  3. Updated views immediately. Re-reading index 0 and length() - 1 now reports 'b' and '!'.

Example 2 — Check Ending Punctuation Before Appending

Inspect the last character of a builder so punctuation is only added when missing.

Java
public class StringBuilderCharAtPunct {
    public static void main(String[] args) {
        String[] notes = {"Saved", "Done!"};
        for (String n : notes) {
            StringBuilder line = new StringBuilder(n);
            if (line.length() > 0 && line.charAt(line.length() - 1) != '!') {
                line.append('.');
            }
            System.out.println(line.toString());
        }
    }
}

How It Works

  1. Guard empty input. Checking line.length() > 0 ensures length() - 1 is never negative.
  2. Inspect tail char. "Saved" ends with 'd' (not '!'), so a period is appended.
  3. Skip when present. "Done!" already ends with '!', leaving it unchanged.

Example 3 — Count Digits Inside a Buffer and Catch Out-of-Range Reads

Loop over a StringBuilder with charAt() to count digits, then catch IndexOutOfBoundsException.

Java
public class StringBuilderCharAtBounds {
    public static void main(String[] args) {
        StringBuilder code = new StringBuilder("ID-409-X");
        int digits = 0;
        for (int i = 0; i < code.length(); i++) {
            if (Character.isDigit(code.charAt(i))) {
                digits++;
            }
        }
        System.out.println("Digits in buffer: " + digits);

        try {
            code.charAt(code.length());
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Caught invalid charAt index");
        }
    }
}

How It Works

  1. Loop up to length(). Iterating 0 <= i < code.length() keeps every charAt(i) read valid.
  2. Classify directly. Character.isDigit checks each char in place, finding '4', '0', and '9'.
  3. Index length() fails. Trying to read one slot past the end raises IndexOutOfBoundsException.

Frequently Asked Questions

No. charAt() is read-only and returns the char at the given zero-based index.
It throws IndexOutOfBoundsException (specifically StringIndexOutOfBoundsException in current JDKs) if index < 0 or index >= length().
Use setCharAt(index, ch), which writes a char at that index in place.
Check if (sb.length() > 0) first, then call sb.charAt(sb.length() - 1).
No. An emoji takes two UTF-16 chars (a surrogate pair), so charAt() only reads one half. Use codePointAt() instead.

Next: codePointAt()

Return the full Unicode code point starting at a given UTF-16 index.

codePointAt() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful