Clear StringBuffer in Java



On clearing the StringBuffer object, all the characters from the buffer will be removed. In this article, we will write Java program to clear the StringBuffer.

StringBuffer is a peer class of String that provides much of the functionality of strings. But, String represents fixed-length, immutable character sequences while StringBuffer represents mutable character sequences.

Example Scenario:

Input: obj = Java Program
Output: res = 

The result will be an empty StringBuffer object.

Using delete() method

The StringBuffer class of java.lang package provides a method named delete() to clear the StringBuffer. This method accepts start and end indices and removes the character within those indices. If we pass 0 as start index and length of StringBuffer object as end index, the delete() method will return an empty object.

Example

Here, we use delete() function to clear the StringBuffer.

public class Buffer {
   public static void main(String[] args) {
      StringBuffer string_buffer = new StringBuffer();
      string_buffer.append("Java");
      string_buffer.append(" Program");
      System.out.println("This string buffer is defined as: " + string_buffer);
      string_buffer.delete(0, string_buffer.length());
      System.out.println("The string buffer after clearing: " + string_buffer);
   }
}

Following is the output of the above code ?

This string buffer is defined as: Java Program
The string buffer after clearing:

Using setLength() method

The setLength() method of Java StringBuffer class is used to set or change the length of a StringBuffer object. If we pass 0 as a parameter value to this method, it will change the length of StringBuffer object to 0.

Example

Here, we use setLength() function to clear the StringBuffer.

public class Buffer {
   public static void main(String[] args) {
      StringBuffer string_buffer = new StringBuffer();
      string_buffer.append("Java");
      string_buffer.append(" Program");
      System.out.println("This string buffer is defined as: " + string_buffer);
      string_buffer.setLength(0);
      System.out.println("The string buffer after clearing: " + string_buffer);
   }
}

Output of the above code is as follows ?

This string buffer is defined as: Java Program
The string buffer after clearing:
Updated on: 2024-08-16T07:36:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements