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. SignatureIf we don't specify endIndex, the method will return all the characters from startIndex. ParametersstartIndex : starting index is inclusive endIndex : ending index is exclusive Returnsspecified string Exception ThrowsStringIndexOutOfBoundsException 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 exampleFileName: SubstringExample.java Test it NowOutput: va vatpoint Java String substring() Method Example 2FileName: SubstringExample2.java Output: Javatpoint point Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 10 Applications of substring() Method1) 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. Next TopicJava String toCharArray() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India