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) returns the characters from index begin up to, but not including, index end. This half-open range, written [begin, end), is used throughout Java: in String, List.subList, Arrays.copyOfRange and the Java 21 indexOf(ch, begin, end). It has three useful properties:

  • The length of the result is simply end - begin.
  • Two ranges that meet, [0, cut) and [cut, length), cover the string exactly once, with no gap and no overlap.
  • An empty range, where begin == end, is valid and gives the empty string.

Indexes count UTF-16 char values, starting at 0. Most characters are one char, but emoji and some rare letters are two, and an accented letter may be a base letter plus a combining mark, which matters when cutting text for display.

In memory, a substring is a new String with its own copy of the characters. Before Java 7 update 6 (JDK-6924259, which removed the offset and count fields from String) it shared the original's character array, which was fast but kept the whole original alive for as long as the small piece existed. That leak is gone; the cost is now a copy proportional to the length of the result.

Ways to take part of a string
APISinceResultBest for
substring(begin)Java 1.0New String to the endEverything after a position
substring(begin, end)Java 1.0New StringAny range of characters
subSequence(begin, end)Java 1.4CharSequence, really a StringCode written against CharSequence
CharBuffer.wrap(s, begin, end)Java 1.4A read-only view, no copyLarge ranges passed to code that accepts CharSequence
offsetByCodePoints + substringJava 5New StringCutting by code points instead of chars
BreakIterator.getCharacterInstanceJava 1.1Boundaries of visible charactersTruncating text shown to users
regionMatches, startsWith(prefix, offset)Java 1.0booleanComparing 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 has exactly 10 characters, with a word boundary at index 4, so every result can be checked against the index ruler in the comment.

Java
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:

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
  • substring(4) runs from index 4 to the end, Script. substring(0, 4) is indexes 0 to 3, Java: the character at 4 is excluded.
  • substring(3, 3) is empty, and so is substring(10): a start equal to the length is allowed and means "nothing left".
  • The first n characters are substring(0, n) and the last n are substring(length - n). substring(1, length - 1) drops one character at each end, which is how quotes or brackets are removed.
  • Splitting at cut and joining the two parts gives back the original exactly, the second property of half-open ranges.
  • Any index outside 0..length, or an end before the start, throws StringIndexOutOfBoundsException. The message shows the range, as in "Range [5, 20) out of bounds for length 10", which makes the bad argument easy to spot.

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.

Java
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:

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
  • left("Java", 10) returns the whole word instead of throwing, because Math.min caps the end at the length. right does the same with Math.max on the start.
  • slice behaves like Python's slicing: -6 means six from the end, so slice(s, -6, 100) is Script and slice(s, 0, -6) is Java. A start after the end gives an empty string.
  • preview leaves short text alone and cuts long text to 17 characters plus ..., 20 in total.
  • between returns an empty string when a marker is missing, instead of passing -1 to substring. The indexOf page explains that trap.
  • removePrefix checks with startsWith before cutting, so a URL with a different scheme is returned unchanged.

Apache Commons Lang has similar lenient methods, such as StringUtils.left and StringUtils.substringBetween, if the project already uses it.

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 is the natural tool, and the third record is deliberately truncated to show the check that such code needs.

Java
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:

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 substring(previousEnd, thisEnd), so the fields fit together without gaps, and changing one width means changing one constant.
  • The name field is padded with spaces to 20 characters, so strip() removes the padding. The amount is right-aligned, so it is stripped before new BigDecimal.
  • The date 20261114 is cut again into year, month and day. LocalDate.parse(d, DateTimeFormatter.BASIC_ISO_DATE) would do the same in one call.
  • 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 values, a cut can land in the middle of something a reader sees as one character. The test strings contain a musical symbol that needs two chars, as emoji do, an Γ© written as e plus a combining accent, and a flag made of two code points.

Java
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:

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)
né πŸ‡©πŸ‡ͺ ok has 11 chars, 9 code points, 7 visible characters
substring(0, 2):         ne|
first 5 code points:     né πŸ‡©|
first 4 visible chars:   né πŸ‡©πŸ‡ͺ|
  • 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 hi, a space, the symbol and ! has 6 chars but 5 code points, and substring(0, 4) ends with a lone high surrogate. Encoding that to UTF-8 replaces it with ?.
  • offsetByCodePoints(0, 4) converts "4 code points" into the char index 5, so the cut keeps the whole symbol.
  • Code points are still not what a reader counts. nΓ© πŸ‡©πŸ‡ͺ ok has 11 chars, 9 code points and 7 visible characters. Cutting at char 2 drops the accent and leaves ne, and cutting after 5 code points leaves half of the flag, which displays as a letter in a box.
  • BreakIterator.getCharacterInstance() finds the boundaries between user-perceived characters, called grapheme clusters, so the preview of 4 keeps nΓ© and the whole flag.

For text shown to users, such as previews and truncated titles, cut on grapheme boundaries. For more on chars and code points, see characters in a string.

What substring costs

Each substring copies its characters, which is invisible for short strings but measurable for large ones and in loops. The program checks when no copy is made, then times copies of a 5 million character range, a view that avoids the copy, and a loop that calls substring repeatedly. Every measurement keeps the fastest of three runs.

Java
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):

Output
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 substring(0) is free. Any shorter range creates a new string. subSequence just calls substring and also returns a String.
  • 100 copies of 5 million characters took around a hundred milliseconds, because each one copies 5 MB. CharBuffer.wrap 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 a CharSequence, such as a Matcher.
  • Repeatedly doing rest = rest.substring(1) 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.

The quadratic pattern also appears in recursive code that passes s.substring(1) to the next call, a common way to write palindrome or parsing exercises. Passing the string and a start index instead keeps it linear. Parsers should likewise move an index forward rather than shorten the string, and keep substring for extracting the final pieces. More measurements are on the string performance page.

Choosing the right call

Choosing how to take part of a string
GoalUse
Everything from a positions.substring(begin)
A range of characterss.substring(begin, end), end excluded
First or last n characters, input may be shorts.substring(0, Math.min(n, s.length())), s.substring(Math.max(0, s.length() - n))
Text after or between markersindexOf + substring, checking for -1
Remove a known prefix or suffixstartsWith or endsWith, then substring
Fixed-width fieldssubstring with named column constants and a length check
Truncate text for displayBreakIterator boundaries, or at least offsetByCodePoints
Pass a large range without copyingCharBuffer.wrap(s, begin, end)
Step through text in a parserAn index variable, not repeated substring
Split on a separatorsplit; see splitting strings