StringBuilder setLength() in Java

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

Syntax:

void java.lang.AbstractStringBuilder.setLength(int newLength)

This method takes one argument of type int as its parameter. This method sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument.

Note:

1. If the newLength argument is less than the current length, the length is changed to the specified length.

2. The newLength argument must be greater than or equal to 0.

Parameters: One parameter is required for this method.

newLength: the new length.

Throws:

StringIndexOutOfBoundsException - if the newLength argument is negative.

Approach 1: When the newLength is greater than or equal to 0.

Java

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

        StringBuilder str = new StringBuilder("Hello");

        int newLength = 100;
        str.setLength(newLength);

        System.out.println(str.length());
    }
}

Output:

100


Approach 2: When the newLength is negative.

Java

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

        StringBuilder str = new StringBuilder("Hello");

        int newLength = -1;
        str.setLength(newLength);

        System.out.println(str.length());
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.base/java.lang.AbstractStringBuilder.setLength(AbstractStringBuilder.java:319) at java.base/java.lang.StringBuilder.setLength(StringBuilder.java:85)


No comments:

Post a Comment