Change the length of the StringBuffer Object in Java


The setLength(int newLength) method is used to change the length of the StringBuffer Object. It sets the length of the character sequence. The character sequence is updated to a new one whose length is determined by the value passed as the parameter in the method. The newLength should be greater than or equal to zero.

The java.lang.StringBuffer(int newLength) method is declared as follows −

public void setLength(int newLength)

Let us see a example program illustrating the use of setLength(int newLength) method

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      StringBuffer sb = new StringBuffer("Hello World");
      System.out.println(sb);
      System.out.println("Original length : "+sb.length());
      System.out.println("Original capacity : "+sb.capacity());
      sb.setLength(5); // changing the length of the StringBuffer object
      System.out.println();
      System.out.println(sb);
      System.out.println("New length : " +sb.length());
      System.out.println("New capacity : " +sb.capacity());
   }
}

Output

Hello World
Original length  : 11
Original capacity : 27
Hello
New length  : 5
New capacity : 27

Updated on: 26-Jun-2020

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements