Java String substring()
The Java String class substring() method returns a part of the string.
We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1.
There are two types of substring methods in Java string.
Signature
If we don’t specify endIndex, the method will return all the characters from startIndex.
Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Returns
specified string
Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.
- if the start index is negative value
- end index is lower than starting index.
- Either starting or ending index is greater than the total number of characters present in the string.
Internal implementation substring(int beginIndex)
Internal implementation substring(int beginIndex, int endIndex)
Java String substring() method example
FileName: SubstringExample.java
Output:
va vatpoint
Java String substring() Method Example 2
FileName: SubstringExample2.java
Output:
Tutoraspire point Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 10
Applications of substring() Method
1) The substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as “singh”. The following program shows the same.
FileName: SubstringExample3.java
Output:
Yuvraj Singh Harbhajan Singh Gurjit Singh Sandeep Singh Milkha Singh
2) The substring() method can also be used to check whether a string is a palindrome or not.
FileName: SubstringExample4.java
Output:
madam is a palindrome. rock is not a palindrome. eye is a palindrome. noon is a palindrome. kill is not a palindrome.