Java StringBuilder substring() Method

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

Definition

In Java, sb.substring(start) and sb.substring(start, end) return a brand-new immutable String holding a slice of the characters in a StringBuilder.

The original StringBuilder is not modified at all, and future edits to the builder will not change the returned String.

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

Syntax

Pass start alone to slice to the end, or pass both start (inclusive) and end (exclusive).

Java
StringBuilder sb = new StringBuilder("Hello, Java!");
String tail = sb.substring(7);      // "Java!" (builder still "Hello, Java!")
String word = sb.substring(7, 11);  // "Java"
CallWhat it does
sb.substring(start)New String from start through sb.length() - 1.
sb.substring(start, end)New String covering indexes start to end - 1.
new StringBuilder(sb.substring(0, 4))Creates a mutable StringBuilder copy from a slice.

If you want to pass a slice straight to a CharSequence parameter (or emphasize read-only sequence access), see subSequence().

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

Parameters

ParameterDescription
start (int)Inclusive start index (0 <= start <= length()).
end (int)Optional exclusive end index (start <= end <= length()).

Return Value

Return ValueDescription
StringA newly created immutable String copy of the specified range.

Compare with Similar Methods

Extracting text from a StringBuilder:

MethodHow it differs
toString()Copies the entire builder into a new String (same as substring(0)).
subSequence(start, end)Returns a CharSequence for the same range (requires both indexes).
getChars(...)Copies a slice into an existing char[] instead of allocating a String.
delete(start, end)Removes the range in place instead of copying it out.

Java Examples

Example 1 — Extract Prefix and Tail Slices Without Mutating the Builder

Read a protocol and host from a URL buffer while keeping the full StringBuilder ready for more appends.

Java
public class StringBuilderSubstringSlice {
    public static void main(String[] args) {
        StringBuilder url = new StringBuilder("https://codetofun.com/java");
        int schemeEnd = url.indexOf("://");
        String scheme = url.substring(0, schemeEnd);
        String rest = url.substring(schemeEnd + 3);

        System.out.println("Scheme: " + scheme);
        System.out.println("Rest:   " + rest);
        System.out.println("Builder intact: " + url);
    }
}

How It Works

  1. Locate separator. indexOf("://") gives 5, marking the exclusive end of the scheme.
  2. Two slice forms. substring(0, 5) takes the prefix and substring(8) takes everything to the end.
  3. Buffer untouched. Printing url proves neither substring call changed its content.

Example 2 — Show That a Substring Snapshot Stays Independent

Take a substring, edit the StringBuilder afterward, and verify the returned String does not change.

Java
public class StringBuilderSubstringSnapshot {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java-2026");
        String prefix = sb.substring(0, 4);

        sb.replace(0, 4, "Python");
        sb.reverse();

        System.out.println("Saved String:    " + prefix);
        System.out.println("Mutated Builder: " + sb);
    }
}

How It Works

  1. Copy slice early. substring(0, 4) allocates an independent immutable String holding "Java".
  2. Edit builder freely. Replacing and reversing sb only modifies the builder's internal array.
  3. Snapshot preserved. prefix still prints Java safely.

Example 3 — Catch StringIndexOutOfBoundsException When end Exceeds length()

Contrast exact length() bounds with an oversized end index that substring() rejects.

Java
public class StringBuilderSubstringBounds {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Code");
        System.out.println("Exact end: '" + sb.substring(2, sb.length()) + "'");
        System.out.println("Empty end: '" + sb.substring(sb.length()) + "'");

        try {
            sb.substring(0, 10);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("end > length() threw StringIndexOutOfBoundsException");
        }
    }
}

How It Works

  1. length() is valid as end. Passing sb.length() (4) as end or start succeeds, returning "de" and "".
  2. No clamping here. Unlike delete(0, 10), substring(0, 10) refuses an end larger than 4.
  3. Exception raised. Out-of-bounds slices fail immediately with StringIndexOutOfBoundsException.

Frequently Asked Questions

It always returns a new immutable String. If you want a mutable slice, pass the result to new StringBuilder(sb.substring(start, end)).
No. It only copies the requested range and leaves the builder unchanged.
delete() clamps end to sb.length(), whereas substring() enforces end <= sb.length() and throws StringIndexOutOfBoundsException when end is too large.
It returns an empty String "" because start == length() is valid at the boundary.
substring() returns a String and has both 1-arg and 2-arg overloads; subSequence() returns a CharSequence and always takes both start and end.

Next: toString()

Create a new String copy of the current builder contents.

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

10 people found this page helpful