Write a Java Program to Clear the StringBuffer

In Java, StringBuffer is a class that represents a mutable sequence of characters.

It is similar to the String class, but the difference is that StringBuffer objects can be modified whereas String objects cannot.


To clear the contents of a StringBuffer, we can use the setLength() method.

The setLength() method sets the length of the StringBuffer to the specified value.

If the new length is less than the current length, the characters beyond the new length are discarded.

If the new length is greater than the current length, null characters (‘\u0000’) are added to the end of the StringBuffer until the length is equal to the new length.

Here’s a Java program to demonstrate how to clear a StringBuffer using the setLength() method:

public class ClearStringBufferExample {
    public static void main(String[] args) {
        // create a StringBuffer
        StringBuffer sb = new StringBuffer("Hello, world!");
        
        // print the original StringBuffer
        System.out.println("Original StringBuffer: " + sb);
        
        // clear the StringBuffer
        sb.setLength(0);
        
        // print the cleared StringBuffer
        System.out.println("Cleared StringBuffer: " + sb);
    }
}

In the above program, we first create a StringBuffer with the text “Hello, world!”.

We then print the original StringBuffer using the println() method.

Next, we call the setLength() method on the StringBuffer and pass 0 as the argument.

This sets the length of the StringBuffer to 0, effectively clearing its contents.

Finally, we print the cleared StringBuffer using the println() method.

The output of the above program will be:

Original StringBuffer: Hello, world!
Cleared StringBuffer: 

As we can see, the original StringBuffer contains the text “Hello, world!”, whereas the cleared StringBuffer is empty.


In conclusion, clearing a StringBuffer in Java is simple and can be done using the setLength() method.

This method sets the length of the StringBuffer to 0, effectively clearing its contents.