Java String subSequence() method with Examples
Last Updated :
04 Dec, 2018
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.
import java.lang.Math;
class Gfg {
public static void main(String args[])
{
String Str = "Welcome to geeksforgeeks" ;
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
import java.lang.Math;
class Gfg {
public static void main(String args[])
{
String Str = "Welcome to geeksforgeeks" ;
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.
import java.lang.Math;
class Gfg {
public static void main(String args[])
{
String Str = "Welcome to geeksforgeeks" ;
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...