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);
//from w w  w  .j ava  2  s .  c o m
    sb.setLength(2);
    System.out.println("buffer after = " + sb);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable