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"
Call
What 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
Parameter
Description
start (int)
Inclusive start index (0 <= start <= length()).
end (int)
Optional exclusive end index (start <= end <= length()).
Return Value
Return Value
Description
String
A newly created immutable String copy of the specified range.