subSequence(): This method is available in java.lang.AbstractStringBuilder class o Java.
Syntax:
CharSequence java.lang.AbstractStringBuilder.subSequence(int start, int end)
This method takes two arguments of type int as its parameters. This method returns a new character sequence that is a subsequence of this sequence.
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 end is greater than length(),or if start is greater than end.
For Example:
StringBuilder str = new StringBuilder("Hello World")
int start = 3, end = 8
str.subSequence(start,end) = > It returns lo Wo.
Approach 1: When the index is in the range.
Java
public class SubSequence {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");int start = 3, end = 8;System.out.println(str.subSequence(start, end));}}
Output:
lo Wo
Approach 2: When the index is out of range.
Java
public class SubSequence {public static void main(String[] args) {StringBuilder str = new StringBuilder("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.StringBuilder.substring(StringBuilder.java:85) at java.base/java.lang.AbstractStringBuilder.subSequence(AbstractStringBuilder.java:1048) at java.base/java.lang.StringBuilder.subSequence(StringBuilder.java:85)
No comments:
Post a Comment