Java Data Type Tutorial - Java StringBuffer.setLength(int newLength)








Syntax

StringBuffer.setLength(int newLength) has the following syntax.

public void setLength(int newLength)

Example

In the following code shows how to use StringBuffer.setLength(int newLength) method.

When you increase the size of the buffer, null characters are added to the end of the existing buffer.

If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.

 
public class Main {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("java2s.com");
    System.out.println("buffer before = " + sb);

    sb.setLength(2);
    System.out.println("buffer after = " + sb);
  }
}

The code above generates the following result.