StringBuffer is a class that facilitates string operations and also helps reduce memory usage. A method defined on StringBuffer named setLength(int newLength) also serves as a shortcut to clear the contents of the StringBuffer.
Listing 1. Code Snippet
public class StringBufferEx{ public static void main(String args[]) { StringBufferEx stringBufferEx = new StringBufferEx(); stringBufferEx.proceed(); } private void proceed() { StringBuffer stringBuffer = new StringBuffer("Initial value"); System.out.println(String.format("%-35s %s" ,"With inital value: ", stringBuffer)); stringBuffer.setLength(0); //Setting the lenght to zero (0), which will also clear the contents of the StringBuffer System.out.println(String.format("%-35s %s" ,"After setting the lenght to zero: ", stringBuffer)); stringBuffer.append("New value"); System.out.println(String.format("%-35s %s" ,"With new value: ", stringBuffer)); }}/*
Listing 2. Expected output
[[email protected]]# java StringBufferExWith inital value: Initial valueAfter setting the lenght to zero:With new value: New value*/