Java String substring() Syntax
substring() is a method of the String class. It has two forms: one takes a begin index, the other a begin index and an end index.
Indexes start at 0. The begin index is inclusive and the end index is exclusive, so the substring has endIndex - beginIndex characters. substring() throws an IndexOutOfBoundsException if beginIndex is negative, endIndex is larger than the string length, or beginIndex is larger than endIndex.
Java Substring Examples
The following are examples of getting a substring in Java. Run them in the online Java code runner and change the indexes to see how the result changes.
Get a substring from an index to the end
With one argument, substring() returns the characters from the begin index to the end of the string.
Get a substring between two indexes
With two arguments, substring() stops before the end index.
Get the first character with substring(0, 1)
substring(0, 1) returns the first character as a String. To get it as a char, use charAt(0).
Get a substring before and after a character
To split a string at a character, find the character with indexOf() and pass its index to substring().