- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Clear the StringBuffer
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:
- Related Articles
- Java program to insert a String into a Substring of StringBuffer
- Java StringBuffer class.
- Is StringBuffer final in Java?
- Java ConcurrentHashMap - clear()
- Change the length of the StringBuffer Object in Java
- Get the capacity of the StringBuffer Object in Java
- Why StringBuffer is mutable in Java?
- Constructors of StringBuffer class in Java.
- Methods of StringBuffer class in Java.
- Java String, StringBuffer and StringBuilder Tutorial.
- How to clear screen using Java?
- How to trim white space in StringBuffer in Java?
- The clear() method of CopyOnWriteArrayListin Java
- What does the StringBuffer append() method do in Java?
- Get the length of a StringBuffer Object in Java

Advertisements