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.
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());
}
}
Output
Java Guide
How It Works
Uppercase first letter.label.charAt(0) reads 'j', and Character.toUpperCase turns it into 'J' at index 0.
Swap separator. Index 4 changes from '-' to a space ' ' without shifting anything.
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);
}
}
}
}
Output
Step 2: [##...]
Step 5: [#####]
How It Works
Pre-filled template. Indexes 1 through 5 hold '.' between the opening and closing brackets.
Overwrite slots 1..5. Each loop step flips one dot directly to '#' without changing length 7.
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");
}
}
}
Output
PIN:***9
Caught out-of-bounds index
How It Works
Leave last digit visible. Indexes 4, 5, and 6 become '*' while index 7 ('9') stays untouched.
setCharAt cannot append. Passing pin.length() (8) targets a slot that does not exist yet.
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).
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.