In this article, we will understand how to clear the StringBuffer. StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.
Below is a demonstration of the same −
Suppose our input is −
This string buffer is defined as: Java Program
The desired output would be −
The string buffer after clearing:
Algorithm
Step 1 - START Step 2 - Declare an object of StringBuffer namely string-buffer. Step 3 - Define the values. Step 4 - Call the inbuilt function .delete() and pass the values 0 and buffer size to clear the buffer. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we use delete() function to clear the buffer.
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); } }
Output
This string buffer is defined as: Java Program The string buffer after clearing:
Example 2
Here, we use setLength() function to clear the buffer.
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
This string buffer is defined as: Java Program The string buffer after clearing: