Java StringBuilder setCharAt() Method

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

Definition

In Java, sb.setCharAt(index, ch) replaces the single char at position index inside a StringBuilder with ch. The length and every other character stay the same.

Unlike append() or replace(), setCharAt() returns void, so it must be called as a standalone statement rather than inside a method chain.

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.setCharAt(...). No import is needed because java.lang is always visible.

Syntax

Pass an existing index (0 <= index < length()) and the replacement char.

Java
StringBuilder sb = new StringBuilder("java");
sb.setCharAt(0, 'J');     // "Java" (standalone statement; returns void)
CallWhat it does
sb.setCharAt(0, 'A')Overwrites the first character with 'A'.
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)))Uppercases the character at index i in place.
sb.setCharAt(sb.length() - 1, '.')Replaces the final character without resizing.

Need to chain another call right afterward, or replace with more or fewer than one char? Use replace(i, i + 1, str) instead.

Library declarations
Java
// java.lang.StringBuilder
public void setCharAt(int index, char ch)

Parameters

ParameterDescription
index (int)Zero-based index to overwrite (0 <= index < length()).
ch (char)The new char value to place at index.

Return Value

Return ValueDescription
voidReturns nothing. You cannot chain calls after setCharAt().

Compare with Similar Methods

Reading and editing single characters:

MethodHow it differs
charAt(index)Reads the character at index without modifying the builder.
replace(i, i + 1, str)Can replace one char or a slice and returns this for chaining.
deleteCharAt(index)Removes the character and shortens the builder instead of overwriting.
Character.toUpperCase(ch)Converts a single char to uppercase to pass into setCharAt().

Java Examples

Example 1 — Capitalize the First Letter and Fix Typos In Place

Read the current character with charAt() and overwrite it with setCharAt().

Java
public class StringBuilderSetCharAtBasic {
    public static void main(String[] args) {
        StringBuilder label = new StringBuilder("java-guide");
        label.setCharAt(0, Character.toUpperCase(label.charAt(0)));
        label.setCharAt(4, ' ');
        label.setCharAt(5, 'G');
        System.out.println(label.toString());
    }
}

How It Works

  1. Uppercase first letter. label.charAt(0) reads 'j', and Character.toUpperCase turns it into 'J' at index 0.
  2. Swap separator. Index 4 changes from '-' to a space ' ' without shifting anything.
  3. Capitalize second word. Index 5 updates from 'g' to 'G', yielding Java Guide.

Example 2 — Update a Progress Bar Buffer In Place

Fill slots step by step inside a single fixed-length builder without allocating new strings.

Java
public class StringBuilderSetCharAtProgress {
    public static void main(String[] args) {
        StringBuilder bar = new StringBuilder("[.....]");
        for (int step = 1; step <= 5; step++) {
            bar.setCharAt(step, '#');
            if (step == 2 || step == 5) {
                System.out.println("Step " + step + ": " + bar);
            }
        }
    }
}

How It Works

  1. Pre-filled template. Indexes 1 through 5 hold '.' between the opening and closing brackets.
  2. Overwrite slots 1..5. Each loop step flips one dot directly to '#' without changing length 7.
  3. Checkpoints printed. At step 2 two bars are filled, and by step 5 all five slots show #.

Example 3 — Mask Characters and Catch IndexOutOfBoundsException

Hide secret PIN digits in place, then test what happens when passing length() as an index.

Java
public class StringBuilderSetCharAtBounds {
    public static void main(String[] args) {
        StringBuilder pin = new StringBuilder("PIN:4829");
        for (int i = 4; i < pin.length() - 1; i++) {
            pin.setCharAt(i, '*');
        }
        System.out.println(pin);

        try {
            pin.setCharAt(pin.length(), '!');
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Caught out-of-bounds index");
        }
    }
}

How It Works

  1. Leave last digit visible. Indexes 4, 5, and 6 become '*' while index 7 ('9') stays untouched.
  2. setCharAt cannot append. Passing pin.length() (8) targets a slot that does not exist yet.
  3. Portable catch block. Catching IndexOutOfBoundsException handles the bounds error cleanly across JDK versions.

Frequently Asked Questions

setCharAt() has a void return type instead of returning StringBuilder. Call it as its own statement, or use replace(i, i + 1, "x") if you want chaining.
No. It overwrites an existing char unit and keeps length() unchanged.
No. Index must satisfy 0 <= index < length(). Passing length() or a negative number throws IndexOutOfBoundsException (StringIndexOutOfBoundsException in current JDKs).
Call sb.setCharAt(i, Character.toUpperCase(sb.charAt(i))).
Because setCharAt works on one 16-bit char unit, overwriting half of a surrogate pair leaves broken text. Use replace(start, end, str) for full code points.

Next: setLength()

Truncate the builder or pad it with NUL (\u0000) chars to reach newLength (returns void).

setLength() 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.

7 people found this page helpful