Java String subSequence() method with Examples
The Java.lang.String.subSequence() is a built-in function in Java that returns a CharSequence. CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at (end-1). The length (in chars) of the returned sequence is (end-start, so if start == end then an empty sequence is returned.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
public CharSequence subSequence(int start, int end) Parameters: start - This is the index from where the subsequence starts, it is inclusive. end - This is the index where the subsequence ends, it is exclusive.
It returns the specified subsequence in range [start, end).
Errors and Exceptions:
IndexOutOfBoundsException – It throws this error if start or end are negative, if end is greater than length(), or if start is greater than end.
Program 1: To show working of Java.lang.String.subSequence() function.
Returns: Welcome Returns: geeksforgeeks
Program 2: To show error of Java.lang.String.subSequence() function when index is negative
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1960) at java.lang.String.subSequence(String.java:2003) at Gfg.main(File.java:15)
Program 3: To show error of Java.lang.String.subSequence() function when index is out of range.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 50 at java.lang.String.substring(String.java:1963) at java.lang.String.subSequence(String.java:2003) at Gfg.main(File.java:16)