The subSequence()
method in Java is used to return a subsequence of a sequence.
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.The subSequence()
method returns the subsequence of the sequence.
Note: The
subSequence()
method throws theIndexOutOfBoundsException
if any of the following conditions are met:
start
is less than 0.end
is less than 0.start
is greater thanend
.end
is greater than the length of the string.
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));}}
A string str
is declared in line 8.
The subSequence()
method is used in line 11 to get the subsequence of str
.