dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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

*/
M S Sridhar
 
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