Write a Java Program to Clear the StringBuffer

Java Program to Clear the StringBuffer

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Clear the StringBuffer
Java Program to Clear the StringBuffer

Write a Java Program to Clear the StringBuffer

PROGRAM: Java Program to Clear the StringBuffer

/*Java Program to Clear the StringBuffer*/

1: Java program to clear using StringBuffer using delete()

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);
}
}

2: 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);
}
}

3: Clear the StringBuffer by creating a new object

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 new
// here new object is created and assigned to str
str = new StringBuffer();
System.out.println(“Updated StringBuffer: ” + str);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *