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.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of setLength 
 * method of StringBuffer class
 */

public class StringBufferSetLength {

	public static void main(String[] args) {		
		
        // initialize the StringBuffer object
        StringBuffer sb = new StringBuffer("java-tutorial");
        System.out.println("Length of buffer:"+sb.length());
        System.out.println("Contents of buffer:"+sb);
        
        
        // set the length of the buffer to 5        
        sb.setLength(5);
        
        // checking the length and contents after setting the length
        System.out.println("New Length of buffer:"+sb.length()); 
        System.out.println("New Contents:"+sb);
       
	}
}

Sample Output :

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

Length of buffer:13
Contents of buffer:java-tutorial
New Length of buffer:5
New Contents:java-

Exception Scenario :

IndexOutOfBoundsException

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

Similar Method :

  • N/A

Suggested Reading List :

References :