Java StringBuffer delete(int start, int end) method

23 Dec 2024 | 2 min read

The delete(int start, int end) method of Java StringBuffer class is used to delete the substring from specified start index to exclusive end index of this sequence. If the start and end index were same then no deletion take place and this sequence remains unchanged.

Syntax:

Parameter:

DataTypeParameterDescription
StringBufferstartThe start index of character sequence.
StringBufferendThe exclusive end index of a character sequence.

Returns:

The delete(int start, int end) method returns this object.

Exception:

StringIndexOutOfBoundsException - if start index is negative or any of index are greater than the length(), or the start index is greater than the end index.

Compatibility Version:

Java 1.2 and above

Example 1

Output:

string1: javatpoint After deleting: jaoint string2: let us learn java After deleting: learn java 

Example 2

Providing the negative (or less than 0) index in delete(int,int) method throws an exception.

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2	at java.lang.AbstractStringBuilder.delete(Unknown Source)	at java.lang.StringBuffer.delete(Unknown Source)	at StringBufferDeleteExample2.main(StringBufferDeleteExample2.java:6) string: javatpoint 

Example 3

Providing the start index and end index as same value, no deletion take place and this sequence remains unchanged.

Output:

string: java code After deleting: java code 

Example 4

Taking the string input from a user in string buffer and using in delete(int,int) method.

Output:

enter your string value: string buffer enter start index: 3 enter end index: 7 count: strbuffer