Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

Java String.substring() method

Reference for Java String.substring(): extract part of a string with begin and end indexes, the end-exclusive rule, exceptions and common patterns.

String.substring() returns a new string containing part of the original. You give a start index, and optionally an end index. The start is inclusive and the end is exclusive, so s.substring(2, 5) returns the characters at positions 2, 3 and 4, which is exactly 5 - 2 = 3 characters.

Since strings are immutable, the original is never changed. Since Java 7u6 the result is an independent copy, so a small substring of a huge string does not keep the big one alive.

Java
"Hello, world".substring(7);      // "world"
"Hello, world".substring(0, 5);   // "Hello"

Try it

Java One and two argument forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Parsing with indexOf and substring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
Name Description
beginIndex First index, inclusive.
endIndex Index after the last character, exclusive. Defaults to length().

Returns: a new String of length endIndex - beginIndex. It may be the same object if the range covers the whole string.

Throws: StringIndexOutOfBoundsException if beginIndex < 0, endIndex > length() or beginIndex > endIndex. NullPointerException on a null string.

Usage notes

  • End is exclusive. The length of the result is always end - begin, which makes slicing arithmetic easy.
  • Empty results are legal. substring(n) with n == length() and substring(i, i) both return "".
  • No negative indexes. Compute from the end with length() - k.
  • subSequence(begin, end) from CharSequence does the same and returns a CharSequence.
  • Surrogate pairs. Indexes are code units; cutting between the two halves of an emoji produces broken text. Use code point offsets (offsetByCodePoints) if you need to be safe.
  • Locating the cut: combine with indexOf() and lastIndexOf(). Check for -1 first, otherwise you slice from the wrong place.
  • Splitting is often clearer with split() when you have a delimiter.
  • Performance. O(n) in the length of the result (it copies), O(1) when the whole string is returned.
  • Java 21 added String.indexOf(ch, from, to) and splitWithDelimiters, but no new substring variants.