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.
If we don't specify endIndex, the method will return all the characters from startIndex.
startIndex : starting index is inclusive
endIndex : ending index is exclusive
StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.
Internal implementation substring(int beginIndex)
Internal implementation substring(int beginIndex, int endIndex)
Java String substring() method example
FileName: SubstringExample.javaTest it Now
Java String substring() Method Example 2
Javatpoint 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.
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.
madam is a palindrome. rock is not a palindrome. eye is a palindrome. noon is a palindrome. kill is not a palindrome.