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








Syntax

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

public void setLength(int newLength)

Example

In the following code shows how to use StringBuilder.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[]) {
    StringBuilder sb = new StringBuilder("java2s.com");
    System.out.println("buffer before = " + sb);

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

The code above generates the following result.