StringBuilder substring() range in Java

substring(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

String java.lang.AbstractStringBuilder.substring(int start, int end)

This method takes two arguments of type int as its parameters. This method returns a new String that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end - 1 (or we can say it returns the substring in the range [start, end) ).

Parameters: Two parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

Returns: The new string.

Throws:

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

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 2, end = 7

str.substring(start,end) = > It returns llo W.

Approach 1: When both the values are in the range.

Java

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

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

        int start = 2, end = 7;
        System.out.println(str.substring(start, end));
    }
}

Output:

llo W


Approach 2: When any value is out of range.

Java

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

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

        int start = 2, end = 15;
        System.out.println(str.substring(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 2, end 15, 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)


No comments:

Post a Comment