StringBuffer delete() Method in Java with Examples
The java.lang.StringBuffer.delete() is an inbuilt method in Java which is used to remove or delete the characters in a substring of this sequence. The substring starts at a specified index start_point and extends to the character at the index end_point.
public StringBuffer delete(int start_point, int end_point)
Parameters : The method accepts two parameters of integer type:
start_point – This refers to the beginning index and is included in the count.
end_point – This refer to the ending index and is excluded from the count.
Return Value : The method returns the string after deleting the substring formed by the range mentioned in the parameters.
Exceptions : StringIndexOutOfBoundsException occurs if the start_point is negative, greater than length(), or greater than the end_point.
Input: String = "Apple" start_point = 2 end_point = 4 Output: Ape Input: String = "GeeksforGeeks" start_point = 2 end_point = 7 Output: GerGeeks
Below programs illustrate the java.lang.StringBuffer.delete() method:
string buffer = Geeksforgeeks After deletion string buffer is = Geeksfgeeks
string buffer = Welcome to Geeksforgeeks After deletion string buffer is = Welcoo Geeksforgeeks
Program 3: Here the index is negative.
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)
Program 4: Here the index is not present.
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)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.