RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Dec 12, 2017

Clearing the Contents of a StringBuffer

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();
   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

[root@mypc]# java StringBufferEx
With inital value:                  Initial value
After setting the lenght to zero:
With new value:                     New value

M S Sridhar
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date