java.lang.StringBuffer setLength(int newLength)

Description :

This java tutorial shows how to use the setLength(newLength) method of StringBuffer class under java.lang package.

The setLength(newLength) method of StringBuffer 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.

Make a  note that if the newLength argument is greater than or equal to the current length, sufficient null characters (‘\u0000’) are appended so that length becomes the newLength argument.

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

Method Syntax :

public void setLength(int newLength)

Parameter Input :

DataType Parameter Description
int newLength the new length

Compatibility Version :

Requires Java 1.0 and up

Java Code Example :

This java example source code demonstrates the use of setLength() method of StringBuffer class. Initially the code assigns a string “java-tutorial” as initial contents of the string buffer. The length of the string is 13. Then we have set the length of the buffer to be five. The code displays the new length and contents of the StringBuffer object.

Sample Output :

Running the setLength(int newLength) method example source code of StringBuffer class will give you the following output

Exception Scenario :

IndexOutOfBoundsException

This above exception will be thrown if the newLength method argument is negative.

Similar Method :

  • N/A

Suggested Reading List :

References :