Google News
logo
Java Program to Clear the StringBuffer
In Java, you can clear the contents of a StringBuffer object using the setLength() method. Here's an example program that demonstrates how to clear a StringBuffer :
Program :
public class StringBufferDemo {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("Hello, world!");
        System.out.println("Before clearing: " + buffer);

        buffer.setLength(0);
        System.out.println("After clearing: " + buffer);
    }
}


In this program, we create a StringBuffer object buffer with the initial value "Hello, world!". We then print the contents of the buffer using System.out.println(). After that, we call the setLength() method with a value of 0 to clear the contents of the buffer. Finally, we print the contents of the buffer again to verify that it has been cleared.

Output :
Before clearing: Hello, world!
After clearing: 
Note that the setLength() method sets the length of the buffer to the specified value. If the specified value is less than the current length of the buffer, the contents of the buffer are truncated.

If the specified value is greater than the current length of the buffer, the buffer is extended with null characters (\0). In this program, we set the length to 0, which effectively clears the contents of the buffer.

Example 2 : Java program to clear using StringBuffer using delete() :

Program :
class Main {
  public static void main(String[] args) {

    // create a string buffer
    StringBuffer str = new StringBuffer();

    // add string to string buffer
    str.append("Java");
    str.append(" is");
    str.append(" popular.");
    System.out.println("StringBuffer: " + str);

    // clear the string
    // using delete()
    str.delete(0, str.length());
    System.out.println("Updated StringBuffer: " + str);
  }
}
Output :
StringBuffer: Java is popular.
Updated StringBuffer: 


In the above example, we have used the delete() method of the StringBuffer class to clear the string buffer.

Here, the delete() method removes all the characters within the specified index numbers.


Clear the StringBuffer using setLength() :

class Main {
  public static void main(String[] args) {

    // create a string buffer
    StringBuffer str = new StringBuffer();

    // add string to string buffer
    str.append("Java");
    str.append(" is");
    str.append(" awesome.");
    System.out.println("StringBuffer: " + str);

    // clear the string
    // using setLength()
    str.setLength(0);
    System.out.println("Updated StringBuffer: " + str);
  }
}


Output :

StringBuffer: Java is awesome.
Updated StringBuffer: 


Here, the setLength() method changes the character sequences present in StringBuffer to a new character sequence. And, set the length of the new character sequence to 0.