Main Tutorials

How to clear / delete the content of StringBuffer()

The StringBuffer is always been using for the String concatenation. However this class didn’t provide a method to clear the existing content. Why there are no clear() function?

You can use the delete(int start, int end) as dirty trick :


sb.delete(0, sb.length());

1 . Example


package com.mkyong.io;

public class App{

   public static void main (String args[]) {

	   StringBuffer sb = new StringBuffer();
	   sb.append("Hello ");
	   sb.append("World ");
	   sb.append("StringBuffer ");
	   
	   //clear the Stringbuffer content
	   sb.delete(0, sb.length());
	   
	   sb.append("String deleted ");
	   
	   System.out.println(sb.toString());	   
	   
   }
}

2. Output


String deleted 

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Meditating-Leo
10 years ago

This was very helpful, thank you.

Laird Nelson
14 years ago

StringBuffer.setLength(0);

Arman
3 years ago
Reply to  mkyong

Thank you so much Bro…had been searching this for a while…Your way got me right..Thanks();

Fatih BAHÇEC?
5 years ago
Reply to  mkyong

Which is more performance

bangaru
12 years ago

m k yong tutorials are worth than any others for me. thanks yong sir.