Java StringBuilder delete() example

In this guide, you will learn about the StringBuilder delete() example method in Java programming and how to use it with an example.

1. StringBuilder delete() example Method Overview


The delete() method of the StringBuilder class is used to remove a subsequence of characters from the current sequence.


stringBuilder.delete(start, end)


- start: The beginning index, inclusive.

- end: The ending index, exclusive.

Key Points:

- The indices are 0-based, which means the first character in the sequence is at index 0.

- If start is equal to end, no changes are made.

- If end is greater than the length of the current sequence, end is adjusted to the end of the sequence.

- It will throw StringIndexOutOfBoundsException if start is negative, greater than length(), or greater than end.

2. StringBuilder delete() example Method Example

public class StringBuilderDeleteExample {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder("Hello, wonderful World!");

        // Deleting "wonderful "
        builder.delete(7, 17);
        System.out.println(builder); // Outputs: Hello, World!

        // Deleting the last character
        builder.delete(builder.length() - 1, builder.length());
        System.out.println(builder); // Outputs: Hello, World

        // Trying to delete with start > end, throws StringIndexOutOfBoundsException
        try {
            builder.delete(5, 3);
        } catch(StringIndexOutOfBoundsException e) {
            System.out.println("Caught an exception: " + e.getMessage());


Hello, World!
Hello, World
Caught an exception: start > end


In the example:

1. We start with a StringBuilder object containing the text "Hello, wonderful World!".

2. We use the delete() method to remove the substring "wonderful " which lies between indices 7 (inclusive) and 17 (exclusive).

3. We then remove the last character using delete(), demonstrating that you can use the length() method for range calculations.

4. Lastly, we purposely provide a start index greater than the end index to demonstrate the StringIndexOutOfBoundsException.

The delete() method provides a convenient way to remove substrings from a StringBuilder object, with the flexibility to specify any start and end index. This method, like other StringBuilder methods, operates in place and does not create new objects, ensuring efficiency in string manipulation operations.

Related Java StringBuilder class method examples