The Java substring() method extracts a part of the string (substring) and returns it.
Example
Syntax of substring()
The syntax of the substring() method is:
string.substring(int startIndex, int endIndex)
substring() Argument
The substring() method can take a maximum of two arguments.
- startIndex - the beginning index
- endIndex (optional) - the ending index
substring() Return Value
The substring() method returns a substring from the given string.
- The substring begins with the character at the startIndex and extends to the character at index
endIndex - 1. - If the endIndex is not passed, the substring begins with the character at the specified index and extends to the end of the string.
Note: You will get an error if
- startIndex/endIndex is negative or greater than string's length
- startIndex is greater than endIndex
Example 1: Java substring() With Only Start Index
Example 2: Java substring() With Start and End Index
If you need to find the index of the first occurrence of the specified substring from the given string, use the Java String indexOf() method.