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.
public class GFG{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("HelloWorld");
sb.delete(5, 10);
System.out.println(sb);
}
}
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.
public class Geeks {
public static void main(String[] args) {
StringBuffer sbf = new StringBuffer("Welcome to Geeksforgeeks");
System.out.println("StringBuffer = " + sbf);
sbf.delete(5, 9);
System.out.println("After deletion = " + sbf);
}
}
Output
StringBuffer = Welcome to Geeksforgeeks After deletion = Welcoo Geeksforgeeks
Example 2: Negative Start Index
Passing a negative index causes an exception.
public class Geeks {
public static void main(String[] args) {
StringBuffer sbf = new StringBuffer("Welcome to Geeksforgeeks");
sbf.delete(-5, 9);
}
}
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.
public class Geeks {
public static void main(String[] args) {
StringBuffer sbf = new StringBuffer("Welcome to Geeksforgeeks");
sbf.delete(99, 109);
}
}
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)