StringBuffer subSequence() in Java

subSequence(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

CharSequence java.lang.StringBuffer.subSequence(int start, int end)

This method takes two arguments of type int as its parameters. This method returns a 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 index end - 1.

Parameters: Two parameters are required for this method.

start: the start index, inclusive.

end: the end index, exclusive.

Returns: the specified subsequence.

Throws:

StringIndexOutOfBoundsException - if start or end is negative, if the end is greater than length(), or if start is greater than the end.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int start = 3, end = 8

str.subSequence(start,end) = > It returns lo Wo.

Approach 1: When the indexes are in the range.

Java

public class SubSequence {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 3, end = 8;
        System.out.println(str.subSequence(start, end));
    }
}

Output:

lo Wo


Approach 2: When the indexes are out of range.

Java

public class SubSequence {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 10, end = 8;
        System.out.println(str.subSequence(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 8, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuffer.subSequence(StringBuffer.java:510)


No comments:

Post a Comment