Java StringBuilder deleteCharAt() Method

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

Definition

In Java, sb.deleteCharAt(index) removes the single char at index inside a StringBuilder, shortening length() by 1 and shifting all later characters left.

It mutates the builder in place and returns this for chaining. Common uses include removing a trailing delimiter and filtering characters one by one.

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

Syntax

Pass the zero-based index of the single char to remove.

Java
StringBuilder sb = new StringBuilder("a,b,c,");
sb.deleteCharAt(sb.length() - 1);   // "a,b,c"
sb.deleteCharAt(1);                 // "ab,c"
CallWhat it does
sb.deleteCharAt(0)Removes the first char in the builder.
sb.deleteCharAt(sb.length() - 1)Drops the trailing character when sb.length() > 0.
sb.deleteCharAt(i).append('!')Chains another call because it returns this.
sb.deleteCharAt(sb.length())Throws StringIndexOutOfBoundsException (index out of range).

deleteCharAt() removes one UTF-16 char unit. For supplementary characters like emoji (2 units), delete the full pair with delete(i, i + Character.charCount(cp)).

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

Parameters

ParameterDescription
index (int)Zero-based position of the char to remove (0 <= index < length()).

Return Value

Return ValueDescription
StringBuilderA reference to this builder for chaining.

Compare with Similar Methods

Ways to remove or overwrite characters:

MethodHow it differs
delete(start, end)Deletes a whole range of characters at once (and clamps end).
setLength(len - 1)Faster way to drop characters specifically from the end (returns void).
setCharAt(index, ch)Overwrites one character in place instead of removing it.
charAt(index)Reads the character at index without modifying the builder.

Java Examples

Example 1 — Trim a Trailing Comma After Building a List

Append items with commas in a loop, then remove the extra comma at the end if the builder is non-empty.

Java
public class StringBuilderDeleteCharAtComma {
    public static void main(String[] args) {
        String[] codes = {"A1", "B2", "C3"};
        StringBuilder sb = new StringBuilder();
        for (String c : codes) {
            sb.append(c).append(',');
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.insert(0, '[').append(']');
        System.out.println(sb.toString());
    }
}

How It Works

  1. Trailing comma built. After three iterations, sb contains "A1,B2,C3," (length 9).
  2. Safe last-index delete. Checking sb.length() > 0 avoids calling deleteCharAt(-1) if the array were empty.
  3. Chain brackets on. After removing index 8, insert and append wrap the clean result in square brackets.

Example 2 — Strip Formatting Characters in a Backward Loop

Walk from length() - 1 down to 0 so deleting consecutive hyphens never skips the next character.

Java
public class StringBuilderDeleteCharAtLoop {
    public static void main(String[] args) {
        StringBuilder id = new StringBuilder("12--34-567");
        for (int i = id.length() - 1; i >= 0; i--) {
            if (id.charAt(i) == '-') {
                id.deleteCharAt(i);
            }
        }
        System.out.println("Digits only: " + id);
    }
}

How It Works

  1. Reverse loop prevents skips. Deleting at index i only shifts characters at indexes above i, which were already inspected.
  2. Adjacent hyphens handled. Even the double hyphen "--" at indexes 2 and 3 is completely removed.
  3. Same builder kept. All edits happen in place, leaving "1234567".

Example 3 — Handle Empty Builders and Out-of-Range Indexes

See why deleteCharAt(length()) and deleting from an empty builder both throw StringIndexOutOfBoundsException.

Java
public class StringBuilderDeleteCharAtBounds {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hi");
        sb.deleteCharAt(1);
        System.out.println("After removing index 1: " + sb);

        try {
            sb.deleteCharAt(sb.length());
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("index == length() threw StringIndexOutOfBoundsException");
        }

        StringBuilder empty = new StringBuilder();
        try {
            empty.deleteCharAt(0);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("empty builder threw StringIndexOutOfBoundsException");
        }
    }
}

How It Works

  1. Valid last index. In "Hi", index 1 holds 'i', so removing it leaves "H" of length 1.
  2. Length is invalid. After shrinking to length 1, index 1 no longer exists and deleteCharAt(sb.length()) throws.
  3. Empty has no valid index. Any deleteCharAt call on a zero-length builder fails immediately with StringIndexOutOfBoundsException.

Frequently Asked Questions

It returns this StringBuilder reference, so you can chain more calls right after deleting a character.
It throws StringIndexOutOfBoundsException. Valid indexes run from 0 to sb.length() - 1.
Each deletion shifts later characters left by one. Walking from length() - 1 down to 0 ensures unvisited indexes stay unchanged.
No, it removes only one UTF-16 char unit and leaves a lone surrogate half. Use delete(i, i + Character.charCount(cp)) for supplementary characters.
setLength(sb.length() - 1) simply updates the length counter without any element checks for shifting, though both are constant time at the very end.

Next: ensureCapacity()

Request that the internal buffer hold at least minimumCapacity chars without resizing again.

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

15 people found this page helpful