How to clear or delete StringBuffer contents in Java

In this article, we will discuss how to clear or delete StringBuffer contents

 

Clearing StringBuffer contents:

Here,

  • Start-index for the contents i.e.; 0
  • end-index which lasts till its length
  • needs to be specified as delete(start, end) method arguments

 

Example 1: To clear or delete all StringBuffer contents:

Method Signature:

public synchronized StringBuffer delete(int start, int end);

Syntax:

sbuffer.delete(0, sbuffer.length());

ClearStringBufferContents.java

package in.bench.resources.sb.operation;

public class ClearStringBufferContents {

	public static void main(String[] args) {

		// Sample StringBuffer
		StringBuffer sbuffer = new StringBuffer();

		// add some contents
		sbuffer.append("Bench");
		sbuffer.append("Resources.");
		sbuffer.append("Net");

		// before clearing sbuffer
		System.out.println("Before clear : "
				+ sbuffer.toString());

		// clear or delete all
		sbuffer.delete(0, sbuffer.length());

		// after clearing sbuffer
		System.out.println("After clear : "
				+ sbuffer.toString());
	}
}

Output

Before clear : BenchResources.Net
After clear : 

Note: In a very similar way, StringBuilder contents can also be cleared

 

We will execute a demo program for StringBuilder as well in the below example

Example 2: To clear or delete all StringBuilder contents:

Method Signature:

public StringBuilder delete(int start, int end);

Syntax:

sbuilder.delete(0, sbuilder.length());

ClearStringBuilderContents.java

package in.bench.resources.sb.operation;

public class ClearStringBuilderContents {

	public static void main(String[] args) {

		// Sample StringBuilder
		StringBuilder sbuilder = new StringBuilder();

		// add some contents
		sbuilder.append("World");
		sbuilder.append("Health");
		sbuilder.append("Organization");

		// before clearing sBuilder
		System.out.println("Before clear : "
				+ sbuilder.toString());

		// clear or delete all
		sbuilder.delete(0, sbuilder.length());

		// after clearing sBuilder
		System.out.println("After clear : "
				+ sbuilder.toString());
	}
}

Output

Before clear : WorldHealthOrganization
After clear : 

 

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

References:

 

Happy Coding !!
Happy Learning !!

How to append new line to StringBuffer in Java
String v/s StringBuffer v/s StringBuilder in Java