java.lang.StringBuilder setLength(int newLength)

Description

On this document we will be showing a java example on how to use the setLength(int newLength) method of StringBuilder Class. Basically the setLength() method of StringBuilder class sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. To make it simpler, if the method argument is less than the current length, the length is changed to the specified length.

As a general rule, newLength method argument must be greater than or equal to 0.

Notes:

  • An IndexOutOfBoundsException will be thrown by the setLength(int newLength) method if the newLength argument is negative.

Method Syntax

public void setLength(int newLength)

Method Argument

Data Type Parameter Description
int newLength the new length of this StringBuilder

Method Returns

The setLength(int newLength) method returns void.

Compatibility

Requires Java 1.5 and up

Java StringBuilder setLength(int newLength) Example

Below is a java code demonstrates the use of setLength(int newLength) method of StringBuilder class. The example presented might be simple however it shows the behavior of the setLength() method.

The java example source code above, demonstrates the use of setCharAt(int index,char ch) method of StringBuilder class. Initially the code assigns a string “java-tutorial” as initial contents of the StringBuilder. The length of the string is 13. Then we have set the length of the StringBuilder to be 5. The code displays the new length and contents of the StringBuilder object. You would noticed that upon setting the length to a shorter value than the contents of the StringBuilder, the contents will be truncated.

It would be interesting to note that if we set the length of the StringBuilder to the higher value than the current length, blank spaces will be appended.

Sample Output

Below is the sample output when you run the above example.

StringBuilder setLength() example output