Return a portion of a string between two indices.
The substring() method returns a new String that is a substring of the original. The substring begins at the specified beginIndex and extends to the character at endIndex - 1. If endIndex is omitted, the substring extends to the end of the string.
The beginIndex is inclusive and the endIndex is exclusive. If beginIndex equals endIndex, an empty string is returned. An IndexOutOfBoundsException is thrown if either index is negative, greater than the string length, or if beginIndex is greater than endIndex.
This method is widely used for extracting portions of strings, such as parsing file extensions, extracting tokens, or trimming known prefixes and suffixes from strings.
| Name | Description | Optional |
|---|---|---|
beginIndex |
The beginning index, inclusive. | No |
endIndex |
The ending index, exclusive. | Yes |
String s = "Hello, World!";
s.substring(7); // "World!"
s.substring(0, 5); // "Hello"