This post will discuss how to clear a StringBuilder or StringBuffer in Java.

1. Using setLength() method

A simple solution to clear a StringBuilder/StringBuffer in Java is calling the setLength(0) method on its instance, which causes its length to change to 0. The setLength() method fills the array used for character storage with zeros and sets the count of characters used to the given length.

Download  Run Code

Output:

I Love Java
I LOVE JAVA

2. Using delete() method

Another solution to remove all characters from the StringBuilder/StringBuffer instance is to call the delete() method for range 0 till its length.

Download  Run Code

Output:

I Love Java
I LOVE JAVA

3. Allocate new instance

Instead of clearing the buffer, you can allocate a new instance of StringBuilder/StringBuffer and let GC do its job. However, repeatedly allocating a new buffer can be more costly than clearing the buffer.

Download  Run Code

Output:

I Love Java
I LOVE JAVA

That’s all about clearing a StringBuilder/StringBuffer in Java.