VOOZH about

URL: https://www.geeksforgeeks.org/java/stringbuffer-delete-method-in-java-with-examples/

⇱ StringBuffer delete() Method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

StringBuffer delete() Method in Java with Examples

Last Updated : 22 Jan, 2026

In Java, the StringBuffer class is used to create mutable sequences of characters. It allows modification of strings without creating new objects. One of the important methods provided by the StringBuffer class is the delete() method, which is used to remove a portion of characters from the string.


Output
Hello

Explanation: Original string: "HelloWorld", Characters from index 5 to 9 are removed. Remaining string becomes "Hello"

Syntax

public StringBuffer delete(int start, int end)

Parameters:

  • start: Starting index (inclusive).
  • end: Ending index (exclusive).

Return Value: Returns the same StringBuffer object after removing the specified substring.

Examples of Delete method

Example 1: Delete Characters from a Sentence

Deletes characters between index 5 and 9.


Output
StringBuffer = Welcome to Geeksforgeeks
After deletion = Welcoo Geeksforgeeks

Example 2: Negative Start Index

Passing a negative index causes an exception.


Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
 String index out of range: -5
 at java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:756)
 at java.lang.StringBuffer.delete(StringBuffer.java:430)
 at geeks.main(geeks.java:13)

Example 3: Index Beyond Length

Using indexes outside the valid range throws an exception.


Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
 at java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:760)
 at java.lang.StringBuffer.delete(StringBuffer.java:430)
 at geeks.main(geeks.java:13)
Comment