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);
//  w  w w  .j a  v  a 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