StringBuilder substring() in Java

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

Syntax:

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

This method takes one argument of type int as its parameter. This method returns a new String that contains a subsequence of characters currently contained in this character sequence. The substring begins at the specified index and extends to the end of this sequence.

Parameters: One parameter is required for this method.

start: The beginning index, inclusive.

Returns: The new string.

Throws:

StringIndexOutOfBoundsException - if start is less than zero, or greater than the length of this object.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 4

str.substring(start) = > It returns o World.

Approach 1: When the index is in the range.

Java

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

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

        int start = 4;
        System.out.println(str.substring(start));
    }
}

Output:

o World


Approach 2: When the index is out of range.

Java

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

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

        int start = 16;
        System.out.println(str.substring(start));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 16, end 11, 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.substring(AbstractStringBuilder.java:1017) at java.base/java.lang.StringBuilder.substring(StringBuilder.java:85)


No comments:

Post a Comment