The subSequence(int start, int end) method of StringBuffer class is the inbuilt method used to return a subsequence of characters lie between index start and end-1 of this sequence. The subsequence starts with the char value at the index start and ends with the char value at (end-1). The length of the returned subsequence is end-start. So if start is equal to end then an empty subsequence is returned.
public CharSequence subSequence?(int start, int end)
This method accepts two parameters:
- start which is Integer type value refers to the start endex of subsequence.
- end which is Integer type value refers to the last endex of subsequence.
This method returns the specified subsequence in range start to end-1.
if start or end are negative, if end is greater than length(), or if start is greater than end then IndexOutOfBoundsException is thrown.
Below programs illustrate the java.lang.StringBuffer.subSequence() method:
String length = 12 and contains = WelcomeGeeks SubSequence = Welcome
String contains = Indian Team Played Well SubSequence = Team Played
Example 3: When start > end:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuffer.substring(AbstractStringBuffer.java:935) at java.lang.StringBuffer.substring(StringBuffer.java:76) at java.lang.AbstractStringBuffer.subSequence(AbstractStringBuffer.java:912) at java.lang.StringBuffer.subSequence(StringBuffer.java:76) at GFG.main(File.java:16)
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.