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.
Syntax:
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.
Returns:
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.
// Java program to demonstrate working // of Java.lang.String.subSequence() method import java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = "Welcome to geeksforgeeks" ; // prints the subsequence from 0-7, exclusive 7th index System.out.print( "Returns: " ); System.out.println(Str.subSequence( 0 , 7 )); System.out.print( "Returns: " ); System.out.println(Str.subSequence( 10 , 24 )); } } |
Output:
Returns: Welcome Returns: geeksforgeeks
Program 2: To show error of Java.lang.String.subSequence() function when index is negative
// Java program to demonstrate error // of Java.lang.String.subSequence() method import java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = "Welcome to geeksforgeeks" ; // throws an error as index is negative System.out.print( "Returns: " ); System.out.println(Str.subSequence(- 1 , 7 )); } } |
Output:
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.
// Java program to demonstrate error // of Java.lang.String.subSequence() method import java.lang.Math; class Gfg { // driver code public static void main(String args[]) { String Str = "Welcome to geeksforgeeks" ; // throws an error as end is out of range System.out.print( "Returns: " ); System.out.println(Str.subSequence( 10 , 50 )); } } |
Output:
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)
Please Login to comment...