Java program to clear the stringbuffer

https:/‮w/‬ww.theitroad.com

To clear a StringBuffer in Java, you can use the setLength() method to set the length of the StringBuffer to 0. Here's an example Java program that demonstrates how to clear a StringBuffer:

public class StringBufferClearExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello, World!");
        System.out.println("Before clearing: " + sb);

        sb.setLength(0);

        System.out.println("After clearing: " + sb);
    }
}

In this program, a StringBuffer is created with the initial value "Hello, World!". The setLength() method is then called on the StringBuffer with an argument of 0, which clears the contents of the StringBuffer.

The program then prints out the contents of the StringBuffer before and after it is cleared. When you run the program, the output should be:

Before clearing: Hello, World!
After clearing:

As you can see, the contents of the StringBuffer are cleared after the setLength() method is called with an argument of 0.