How to Delete StringBuffer Elements Or Clear StringBuffer in Java


The example aims to show how to remove a section of characters, or delete a single specific character, or clear entire content of a StringBuffer object.

Source Code

package com.beginner.examples;

public class StringBufferDelete {

	public static void main(String[] args) {
		
		//Create StringBuffe.
		StringBuffer stringBuffer = new StringBuffer("Hello World");
		
		System.out.println("Before deletion , StringBuffer is : " + stringBuffer);
		
		/*
		 * To delete the characters from StringBuffer use the method delete(int start, int end).
		 */
		stringBuffer.delete(0,6);
		System.out.println("After deletion , StringBuffer is : " + stringBuffer);
		
		/*
		 * To delete the character at specified index use the method deleteCharAt(int index).
		 */
		stringBuffer.deleteCharAt(0);
		System.out.println("After deleting a particular element , StringBuffer is : " + stringBuffer);
		
		/*
		 * To clear contents of a StringBuffer use the method delete(int start, int end).
		 */
		stringBuffer.delete(0, stringBuffer.length());
		System.out.println("After clearing all the elements , StringBuffer is : " + stringBuffer);

	}

}

Output:

Before deletion , StringBuffer is : Hello World
After deletion , StringBuffer is : World
After deleting a particular element , StringBuffer is : orld
After clearing all the elements , StringBuffer is : 
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments