Clearing the Contents of a StringBuffer

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

[root@mypc]# java StringBufferExWith inital value:                  Initial valueAfter setting the lenght to zero:With new value:                     New value*/

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist