Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Clearing the Contents of a StringBuffer

StringBuffer is a class that facilitates string operations and also helps reduce memory usage.


advertisement

WEBINAR:

On-Demand

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017


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 StringBufferEx
With inital value:                  Initial value
After setting the lenght to zero:
With new value:                     New value

*/

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date