Java StringBuffer subSequence() method returns a sub sequence based on the start and end indexes. As we know, StringBuffer is a char sequence, the subSequence() method returns a subset of this sequence.
Syntax of subSequence() method
//returns the char sequence from index 3 to 6 //3 is inclusive and 6 is exclusive CharSequence cs = sb.subSequence(3, 6);
Here, sb is an object of StringBuffer class.
subSequence() Description
public CharSequence subSequence(int start, int end): It returns a subsequence from the existing StringBuffer sequence using the start and end indexes.
subSequence() Parameters
This method takes two parameters:
- start: It is an integer index that represents the start of the subsequence. It is inclusive.
- end: Integer index that represents the end of the subsequence. It is exclusive
subSequence() Return Value
- It returns a new char sequence which is a subset of the old char sequence.
It throws IndexOutOfBoundsException, if any of the following condition occurs:
start < 0orend <0end >= sb.length()start > end
Example 1: Get subsequence from an existing sequence
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Good luck");
System.out.println("Sequence: "+sb);
//getting sub sequence from index 5 to 9
CharSequence cs = sb.subSequence(5, 9);
System.out.println("Sub sequence: "+cs);
}
}
Output:

Example 2: Exclude first and last character from sequence
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
System.out.println("Given Sequence: "+sb);
//from 2nd char till 2nd last char
CharSequence cs = sb.subSequence(1, sb.length()-1);
System.out.println("Sub sequence: "+cs);
}
}
Output:

Example 3: If start index is greater than end index
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
System.out.println("Given Sequence: "+sb);
//if start index > end index
CharSequence cs = sb.subSequence(2, 1);
System.out.println("Sub sequence: "+cs);
}
}
Output:
