substring
substring returns part of a string chosen by position: the start index is included and the end index is not, so the result has end minus start characters. This page explains that convention and what substring does in memory, then builds helpers that never throw, parses fixed-width records, shows how emoji and accents get cut in half, and measures what copying costs.
Contents
How substring works
substring(begin, end)beginend[begin, end)StringList.subListArrays.copyOfRangeindexOf(ch, begin, end)
- The length of the result is simply
.end - begin - Two ranges that meet,
and[0, cut) , cover the string exactly once, with no gap and no overlap.[cut, length) - An empty range, where
, is valid and gives the empty string.begin == end
Indexes count UTF-16 charchar
In memory, a substring is a new StringoffsetcountString
| API | Since | Result | Best for |
|---|---|---|---|
substring(begin) | Java 1.0 | New String | Everything after a position |
substring(begin, end) | Java 1.0 | New String | Any range of characters |
subSequence(begin, end) | Java 1.4 | CharSequenceString | Code written against CharSequence |
CharBuffer.wrap(s, begin, end) | Java 1.4 | A read-only view, no copy | Large ranges passed to code that accepts CharSequence |
offsetByCodePointssubstring | Java 5 | New String | Cutting by code points instead of chars |
BreakIterator.getCharacterInstance | Java 1.1 | Boundaries of visible characters | Truncating text shown to users |
regionMatchesstartsWith(prefix, offset) | Java 1.0 | boolean | Comparing a range without extracting it |
The programs below are complete classes, compiled and run on JDK 21.
The two forms and the index rules
JavaScript
public class SubstringDemo {
public static void main(String[] args) {
String s = "JavaScript";
// 0123456789
System.out.println("substring(4) = " + s.substring(4)); // from 4 to the end
System.out.println("substring(0, 4) = " + s.substring(0, 4)); // 0..3, end excluded
System.out.println("substring(4, 7) = " + s.substring(4, 7));
System.out.println("substring(3, 3) = [" + s.substring(3, 3) + "] (empty)");
System.out.println("substring(10) = [" + s.substring(10) + "] (begin == length)");
System.out.println("length of substring(2, 6) is 6 - 2 = " + s.substring(2, 6).length());
// First and last n characters
int n = 3;
System.out.println("first 3: " + s.substring(0, n));
System.out.println("last 3: " + s.substring(s.length() - n));
System.out.println("drop first and last: " + s.substring(1, s.length() - 1));
// Adjacent ranges join back to the original with no gap or overlap
int cut = 4;
System.out.println("rejoined: " + (s.substring(0, cut) + s.substring(cut)).equals(s));
// Out-of-range indexes throw
try {
s.substring(5, 20);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("substring(5, 20): " + e.getMessage());
}
try {
s.substring(6, 2);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("substring(6, 2): " + e.getMessage());
}
try {
s.substring(-1);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("substring(-1): " + e.getMessage());
}
}
}
Output:
substring(4) = Script
substring(0, 4) = Java
substring(4, 7) = Scr
substring(3, 3) = [] (empty)
substring(10) = [] (begin == length)
length of substring(2, 6) is 6 - 2 = 4
first 3: Jav
last 3: ipt
drop first and last: avaScrip
rejoined: true
substring(5, 20): Range [5, 20) out of bounds for length 10
substring(6, 2): Range [6, 2) out of bounds for length 10
substring(-1): Range [-1, 10) out of bounds for length 10
runs from index 4 to the end,substring(4) .Script is indexes 0 to 3,substring(0, 4) : the character at 4 is excluded.Java is empty, and so issubstring(3, 3) : a start equal to the length is allowed and means "nothing left".substring(10)- The first n characters are
and the last n aresubstring(0, n) .substring(length - n) drops one character at each end, which is how quotes or brackets are removed.substring(1, length - 1) - Splitting at
and joining the two parts gives back the original exactly, the second property of half-open ranges.cut - Any index outside
, or an end before the start, throws0..length . The message shows the range, as in "Range [5, 20) out of bounds for length 10", which makes the bad argument easy to spot.StringIndexOutOfBoundsException
Helpers that never throw
Many substring calls only fail on unusual input, such as a name shorter than expected. The helpers below clamp indexes instead of throwing, and the test values are chosen to hit the edge cases: a request for more characters than exist, negative indexes, and missing markers.
public class SafeSubstring {
// First n characters, or the whole string if it is shorter
static String left(String s, int n) {
return s.substring(0, Math.min(n, s.length()));
}
// Last n characters, or the whole string if it is shorter
static String right(String s, int n) {
return s.substring(Math.max(0, s.length() - n));
}
// Python-style: negative indexes count from the end, out-of-range values are clamped
static String slice(String s, int begin, int end) {
int len = s.length();
int b = Math.max(0, Math.min(len, begin < 0 ? len + begin : begin));
int e = Math.max(b, Math.min(len, end < 0 ? len + end : end));
return s.substring(b, e);
}
// Shorten long text for display, without throwing on short input
static String preview(String text, int max) {
return text.length() <= max ? text : text.substring(0, max - 3) + "...";
}
// Text between two markers, or "" if either is missing
static String between(String text, String open, String close) {
int start = text.indexOf(open);
if (start < 0) {
return "";
}
start += open.length();
int end = text.indexOf(close, start);
return end < 0 ? "" : text.substring(start, end);
}
// Remove a prefix only if it is there
static String removePrefix(String s, String prefix) {
return s.startsWith(prefix) ? s.substring(prefix.length()) : s;
}
public static void main(String[] args) {
System.out.println("left(\"Java\", 10) = " + left("Java", 10));
System.out.println("right(\"Java\", 2) = " + right("Java", 2));
System.out.println("slice(\"JavaScript\", -6, 100) = " + slice("JavaScript", -6, 100));
System.out.println("slice(\"JavaScript\", 0, -6) = " + slice("JavaScript", 0, -6));
System.out.println("slice(\"JavaScript\", 8, 2) = [" + slice("JavaScript", 8, 2) + "]");
System.out.println(preview("A short title", 20));
System.out.println(preview("A considerably longer article title", 20));
System.out.println(between("<b>bold</b> text", "<b>", "</b>"));
System.out.println("[" + between("no markers here", "<b>", "</b>") + "]");
System.out.println(removePrefix("https://example.com", "https://"));
System.out.println(removePrefix("ftp://example.com", "https://"));
}
}
Output:
left("Java", 10) = Java
right("Java", 2) = va
slice("JavaScript", -6, 100) = Script
slice("JavaScript", 0, -6) = Java
slice("JavaScript", 8, 2) = []
A short title
A considerably lo...
bold
[]
example.com
ftp://example.com
returns the whole word instead of throwing, becauseleft("Java", 10) caps the end at the length.Math.min does the same withright on the start.Math.max behaves like Python's slicing:slice means six from the end, so-6 isslice(s, -6, 100) andScript isslice(s, 0, -6) . A start after the end gives an empty string.Java leaves short text alone and cuts long text to 17 characters pluspreview , 20 in total.... returns an empty string when a marker is missing, instead of passing -1 tobetween . ThesubstringindexOf page explains that trap. checks withremovePrefix before cutting, so a URL with a different scheme is returned unchanged.startsWith
Apache Commons Lang has similar lenient methods, such as StringUtils.leftStringUtils.substringBetween
Parsing fixed-width records
Banking, airline and mainframe systems still exchange files where each field sits at fixed character positions instead of being separated by commas. This is where substring
import java.math.BigDecimal;
import java.time.LocalDate;
public class FixedWidth {
// Column positions of a fixed-width record: [begin, end)
static final int ID_END = 6;
static final int NAME_END = 26;
static final int DATE_END = 34;
static final int AMOUNT_END = 44;
public static void main(String[] args) {
String[] records = {
"000042Ada Lovelace 20261114 150.25",
"000043Alan Turing 20261201 9.99",
"000044Grace Hopper 2026",
};
System.out.println("0 1 2 3 4");
System.out.println("01234567890123456789012345678901234567890123");
System.out.println(records[0]);
for (String r : records) {
if (r.length() < AMOUNT_END) {
System.out.println("short record (" + r.length() + " chars), id "
+ r.substring(0, ID_END));
continue;
}
int id = Integer.parseInt(r.substring(0, ID_END));
String name = r.substring(ID_END, NAME_END).strip();
String d = r.substring(NAME_END, DATE_END);
LocalDate date = LocalDate.of(Integer.parseInt(d.substring(0, 4)),
Integer.parseInt(d.substring(4, 6)), Integer.parseInt(d.substring(6)));
BigDecimal amount = new BigDecimal(r.substring(DATE_END, AMOUNT_END).strip());
System.out.printf("id=%d name=%s date=%s amount=%s%n", id, name, date, amount);
}
}
}
Output:
0 1 2 3 4
01234567890123456789012345678901234567890123
000042Ada Lovelace 20261114 150.25
id=42 name=Ada Lovelace date=2026-11-14 amount=150.25
id=43 name=Alan Turing date=2026-12-01 amount=9.99
short record (30 chars), id 000044
- The record layout is kept in named constants. Each field is
, so the fields fit together without gaps, and changing one width means changing one constant.substring(previousEnd, thisEnd) - The name field is padded with spaces to 20 characters, so
removes the padding. The amount is right-aligned, so it is stripped beforestrip() .new BigDecimal - The date
is cut again into year, month and day.20261114 would do the same in one call.LocalDate.parse(d, DateTimeFormatter.BASIC_ISO_DATE) - The third record has only 30 characters, so the code checks the length first and reports it instead of throwing on
.substring(34, 44)
Cutting emoji and accents in half
Because indexes count charΓ©e
import java.text.BreakIterator;
public class UnicodeCut {
public static void main(String[] args) {
// The G clef symbol U+1D11E is outside the BMP: two chars (a surrogate pair)
String s = "hi \uD834\uDD1E!";
System.out.println(s + " has " + s.length() + " chars, "
+ s.codePointCount(0, s.length()) + " code points");
String broken = s.substring(0, 4);
System.out.println("substring(0, 4) ends in a lone surrogate: "
+ Character.isHighSurrogate(broken.charAt(3)));
System.out.println("as UTF-8 bytes it becomes '?': "
+ new String(broken.getBytes(java.nio.charset.StandardCharsets.UTF_8),
java.nio.charset.StandardCharsets.UTF_8));
// Cut by code points: offsetByCodePoints converts a code point count to a char index
int end = s.offsetByCodePoints(0, 4);
System.out.println("first 4 code points: " + s.substring(0, end)
+ " (char index " + end + ")");
// What a reader sees as one character can be several code points
String t = "ne\u0301 \uD83C\uDDE9\uD83C\uDDEA ok"; // "nΓ©", German flag, "ok"
System.out.println(t + " has " + t.length() + " chars, "
+ t.codePointCount(0, t.length()) + " code points, "
+ graphemes(t) + " visible characters");
System.out.println("substring(0, 2): " + t.substring(0, 2) + "|");
System.out.println("first 5 code points: " + t.substring(0, t.offsetByCodePoints(0, 5))
+ "|");
System.out.println("first 4 visible chars: " + previewGraphemes(t, 4) + "|");
}
static int graphemes(String s) {
BreakIterator it = BreakIterator.getCharacterInstance();
it.setText(s);
int count = 0;
while (it.next() != BreakIterator.DONE) {
count++;
}
return count;
}
// Keeps at most n user-perceived characters, never cutting one in half
static String previewGraphemes(String s, int n) {
BreakIterator it = BreakIterator.getCharacterInstance();
it.setText(s);
int end = 0;
for (int i = 0; i < n && it.next() != BreakIterator.DONE; i++) {
end = it.current();
}
return s.substring(0, end);
}
}
Output:
hi π! has 6 chars, 5 code points
substring(0, 4) ends in a lone surrogate: true
as UTF-8 bytes it becomes '?': hi ?
first 4 code points: hi π (char index 5)
neΜ π©πͺ ok has 11 chars, 9 code points, 7 visible characters
substring(0, 2): ne|
first 5 code points: neΜ π©|
first 4 visible chars: neΜ π©πͺ|
- The G clef symbol, U+1D11E, is outside the Basic Multilingual Plane, like most emoji, so it is stored as a surrogate pair. The test string
, a space, the symbol andhi has 6 chars but 5 code points, and! ends with a lone high surrogate. Encoding that to UTF-8 replaces it withsubstring(0, 4) .? converts "4 code points" into the char index 5, so the cut keeps the whole symbol.offsetByCodePoints(0, 4)- Code points are still not what a reader counts.
has 11 chars, 9 code points and 7 visible characters. Cutting at char 2 drops the accent and leavesnΓ© π©πͺ ok , and cutting after 5 code points leaves half of the flag, which displays as a letter in a box.ne finds the boundaries between user-perceived characters, called grapheme clusters, so the preview of 4 keepsBreakIterator.getCharacterInstance() and the whole flag.nΓ©
For text shown to users, such as previews and truncated titles, cut on grapheme boundaries. For more on chars and code points, see
What substring costs
Each substringsubstring
import java.nio.CharBuffer;
public class CopyCost {
static long sink;
public static void main(String[] args) {
String s = "JavaScript";
System.out.println("substring(0) == s: " + (s.substring(0) == s));
System.out.println("substring(0, length) == s: " + (s.substring(0, s.length()) == s));
System.out.println("substring(1) == s: " + (s.substring(1) == s));
CharSequence part = s.subSequence(0, 4);
System.out.println("subSequence(0, 4) is String: " + (part instanceof String));
// A large string: each substring copies its characters
String big = "x".repeat(10000000);
time("100 x substring of 5M chars", () -> {
for (int i = 0; i < 100; i++) {
sink += big.substring(1, 5000001).length();
}
});
// A CharBuffer view shares the characters instead of copying them
time("100 x CharBuffer.wrap view", () -> {
for (int i = 0; i < 100; i++) {
sink += CharBuffer.wrap(big, 1, 5000001).length();
}
});
// Removing one character at a time with substring is quadratic
String text = "y".repeat(50000);
time("50,000 x substring(1) loop", () -> {
String rest = text;
while (!rest.isEmpty()) {
rest = rest.substring(1);
}
});
time("index loop over 50,000 chars", () -> {
for (int i = 0; i < text.length(); i++) {
sink += text.charAt(i);
}
});
}
// Best of 3 runs
static void time(String name, Runnable work) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
work.run();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-30s %7.2f ms%n", name, best / 1e6);
}
}
Output (a rough comparison; 2-CPU Linux machine, JDK 21):
substring(0) == s: true
substring(0, length) == s: true
substring(1) == s: false
subSequence(0, 4) is String: true
100 x substring of 5M chars 122.06 ms
100 x CharBuffer.wrap view 0.04 ms
50,000 x substring(1) loop 142.73 ms
index loop over 50,000 chars 0.35 ms
- A substring that covers the whole string returns the original object, so
is free. Any shorter range creates a new string.substring(0) just callssubSequence and also returns asubstring .String - 100 copies of 5 million characters took around a hundred milliseconds, because each one copies 5 MB.
creates a view over the same characters and was more than a hundred times faster. It is useful when the range is large and the receiving code accepts aCharBuffer.wrap , such as aCharSequence .Matcher - Repeatedly doing
copies the remaining text on every step, so the total work grows with the square of the length: 50,000 characters meant about 1.25 billion characters copied. Walking an index over the string visited every character in a tiny fraction of that time, because it copies nothing.rest = rest.substring(1)
The quadratic pattern also appears in recursive code that passes s.substring(1)substring
Choosing the right call
| Goal | Use |
|---|---|
| Everything from a position | s.substring(begin) |
| A range of characters | s.substring(begin, end) |
| First or last n characters, input may be short | s.substring(0, Math.min(n, s.length()))s.substring(Math.max(0, s.length() - n)) |
| Text after or between markers | indexOfsubstring |
| Remove a known prefix or suffix | startsWithendsWithsubstring |
| Fixed-width fields | substring |
| Truncate text for display | BreakIteratoroffsetByCodePoints |
| Pass a large range without copying | CharBuffer.wrap(s, begin, end) |
| Step through text in a parser | An index variable, not repeated substring |
| Split on a separator | split |