What is the string subSequence() method in Java?
The subSequence() method in Java is used to return a subsequence of a sequence.
Syntax
The subSequence() method can be declared as shown in the code snippet below:
public CharSequence subSequence(int start, int end)
start(inclusive): The index from which the subsequence will start.end(exclusive): The index at which the subsequence will end.
Return value
The subSequence() method returns the subsequence of the sequence.
Note: The
subSequence()method throws theIndexOutOfBoundsExceptionif any of the following conditions are met:
startis less than 0.endis less than 0.startis greater thanend.endis greater than the length of the string.
Example
Consider the code snippet below, which demonstrates the use of the subSequence() method.
import java.lang.Math;class Main {public static void main(String args[]){String str = "subSequence() example";System.out.println("str: " + str);System.out.println("subStr: " + str.subSequence(0, 13));}}
Explanation
A string str is declared in line 8.
The subSequence() method is used in line 11 to get the subsequence of str.