Java StringBuilder delete() Method

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

Definition

In Java, sb.delete(start, end) removes the characters from index start (inclusive) up to end (exclusive) inside a StringBuilder, shifting later characters left.

It edits the builder in place and returns this for chaining. When start == end, nothing is removed.

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

Syntax

Pass the inclusive start index and exclusive end index.

Java
StringBuilder sb = new StringBuilder("Hello, World!");
sb.delete(5, 7);          // "HelloWorld!" (removes ", ")
sb.delete(5, 999);        // "Hello" (end > length() is clamped)
CallWhat it does
sb.delete(0, 5)Deletes the first five characters (indexes 0 to 4).
sb.delete(pos, sb.length())Removes everything from pos to the end.
sb.delete(pos, 1000)Safe tail cut: end is clamped to sb.length().
sb.delete(0, sb.length())Clears all characters while keeping buffer capacity.

To remove only one character by position, deleteCharAt() is shorter; to clear everything quickly, setLength(0) works too.

Library declarations
Java
// java.lang.StringBuilder
public StringBuilder delete(int start, int end)

Parameters

ParameterDescription
start (int)Inclusive zero-based start index (0 <= start <= length()).
end (int)Exclusive end index (end >= start). Values above length() are clamped to length().

Return Value

Return ValueDescription
StringBuilderA reference to this builder for chaining.

Compare with Similar Methods

Removing or shrinking text in a StringBuilder:

MethodHow it differs
deleteCharAt(index)Deletes one char at a single index.
replace(start, end, "")Has the exact same effect as delete(start, end).
setLength(n)Truncates from the end to length n (returns void).
substring(start, end)Reads a slice as a String without changing the builder (does not clamp end).

Java Examples

Example 1 — Remove a Prefix and a Middle Word

Delete a status prefix first, then chain a second deletion inside the remaining text.

Java
public class StringBuilderDeleteBasic {
    public static void main(String[] args) {
        StringBuilder msg = new StringBuilder("Error: file missing");
        msg.delete(0, 7);
        System.out.println("After prefix cut: " + msg);

        StringBuilder path = new StringBuilder("alpha-beta-gamma");
        path.delete(5, 10);
        System.out.println("Middle removed:   " + path);
    }
}

How It Works

  1. Zero-based range. Deleting indexes 0 through 6 (delete(0, 7)) removes "Error: " from the start.
  2. Middle splice. Removing indexes 5 through 9 deletes "-beta", pulling "-gamma" straight after "alpha".
  3. In-place edits. Neither call allocates a new StringBuilder; both shift characters inside the original objects.

Example 2 — How end Clamping Works vs Invalid start > end

Pass an end past length() to remove the tail safely, then catch an inverted range.

Java
public class StringBuilderDeleteClamp {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello, World!");
        sb.delete(5, 100);
        System.out.println("Clamped delete(5, 100): " + sb);

        try {
            sb.delete(4, 2);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("start > end threw StringIndexOutOfBoundsException");
        }
    }
}

How It Works

  1. Automatic clamping. Even though length is 13, delete(5, 100) clamps 100 to 13 and cuts ", World!" cleanly.
  2. Exact result left. Characters 0 through 4 stay untouched, leaving Hello.
  3. Invalid order throws. When start (4) exceeds end (2), Java rejects the range with StringIndexOutOfBoundsException.

Example 3 — Find a Tag With indexOf() and Delete It

Locate " [draft]" dynamically and remove it, then clear the builder while keeping its capacity.

Java
public class StringBuilderDeleteSearch {
    public static void main(String[] args) {
        StringBuilder title = new StringBuilder("Annual Report [draft] v2");
        String tag = " [draft]";
        int pos = title.indexOf(tag);
        if (pos != -1) {
            title.delete(pos, pos + tag.length());
        }
        System.out.println("Published title: " + title);

        int capBefore = title.capacity();
        title.delete(0, title.length());
        System.out.println("Empty length = " + title.length() + ", same capacity? " + (title.capacity() == capBefore));
    }
}

How It Works

  1. Locate first. indexOf(" [draft]") finds index 13, avoiding hard-coded numbers.
  2. Remove exact span. Deleting from pos to pos + tag.length() cuts only the marker and its leading space.
  3. Buffer retained. Clearing from 0 to length() drops length to 0 while keeping the allocated capacity ready for reuse.

Frequently Asked Questions

start is inclusive and end is exclusive. Calling sb.delete(1, 4) deletes indexes 1, 2, and 3, keeping index 4.
It is clamped to sb.length(), so sb.delete(start, 999) removes characters from start through the end without throwing.
When start is negative, start is greater than length(), or start is greater than end.
No. It reduces length() and shifts remaining chars, while capacity() stays at its existing size.
Call sb.delete(0, sb.length()) or sb.setLength(0). Both reset length() to 0 without shrinking capacity().

Next: deleteCharAt()

Remove a single char at an index and shift the remaining characters left.

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

14 people found this page helpful