StringBuilder delete() in Java with Examples

Last Updated : 9 Jan, 2026

The delete(int start, int end) method of the StringBuilder class removes a sequence of characters from the string represented by the StringBuilder object. Characters are deleted starting from index start (inclusive) up to end - 1 (exclusive).

Syntax

public StringBuilder delete(int start, int end)

Parameters: This method accepts two parameters: 

  • start:index of the first character to be removed (inclusive).
  • end:index after the last character to be removed (exclusive).

Return Value: This method returns this StringBuilder object after removing the substring.

Example 1: Deleting a Substring 

Java
class GFG {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("WelcomeGeeks");
        System.out.println("Before removal String = " + str);

        str.delete(2, 8);
        System.out.println("After removal String = " + str);
    }
}

Output
Before removal String = WelcomeGeeks
After removal String = Weeeks

Explanation: Characters from index 2 to 7 ("lcomeG") are removed, and the remaining string is returned.

Example 2: When start Equals end

Java
class GFG {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("GeeksforGeeks");
        System.out.println("Before removal String = " + str);

        str.delete(8, 8);
        System.out.println("After delete(8, 8) => " + str);

        str.delete(1, 8);
        System.out.println("After delete(1, 8) => " + str);
    }
}

Output
Before removal String = GeeksforGeeks
After delete(8, 8) => GeeksforGeeks
After delete(1, 8) => GGeeks

Explanation: delete(8, 8) removes nothing because the range is empty while delete(1, 8) removes characters from index 1 to 7

Example 3: Demonstrating Exception

Java
class GFG {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("GeeksforGeeks");
        try {
            str.delete(7, 4);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

Output
Exception: java.lang.StringIndexOutOfBoundsException: Range [7, 4) out of bounds for length 13

Explanation: An exception is thrown because start is greater than end, which is an invalid range.

Method

Purpose

delete(start, end)

Removes a range of characters

deleteCharAt(index)

Removes a single character

substring(start, end)

Returns a new string without modifying original

Comment