In Java, sb.subSequence(start, end) returns a CharSequence containing the characters from index start (inclusive) to end (exclusive) without modifying the StringBuilder.
StringBuilder implements the CharSequence interface (alongside String and CharBuffer), so subSequence() lets you pass a slice directly to methods that accept any CharSequence.
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.subSequence(...). No import is needed because java.lang is always visible.
Syntax
Pass both inclusive start and exclusive end indexes.
Passes a slice straight into another builder's append(CharSequence).
word.contentEquals(sb.subSequence(2, 6))
Compares a String directly against a builder slice.
In OpenJDK, StringBuilder.subSequence(start, end) delegates to substring(start, end), though its declared return type is CharSequence rather than String.
Library declarations
Java
// java.lang.StringBuilder
public CharSequence subSequence(int start, int end)
Parameters
Parameter
Description
start (int)
Inclusive zero-based start index (0 <= start <= end).
end (int)
Exclusive end index (start <= end <= length()).
Return Value
Return Value
Description
CharSequence
A CharSequence holding the characters in [start, end).
Zero-length slice valid. When start == end, zero characters lie in the half-open interval [2, 2).
Invalid order caught. Passing start > end (3 > 1) throws IndexOutOfBoundsException.
Original unaffected. Calling subSequence never shrinks or changes sb.
Frequently Asked Questions
StringBuilder implements the CharSequence interface, which requires subSequence(int start, int end). substring() returns a String directly and also offers a one-argument overload.
No. It leaves the StringBuilder unchanged.
In standard OpenJDK implementations it delegates to substring() and returns an independent String, though the method signature only guarantees a CharSequence with the sliced characters.
No. subSequence always requires both start and end indexes; use substring(start) for one argument.
It throws IndexOutOfBoundsException (specifically StringIndexOutOfBoundsException in current JDKs).