Home »
Java programming language
Java StringBuilder delete() method with example
StringBuilder Class delete() method: Here, we are going to learn about the delete() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 22, 2019
StringBuilder Class delete() method
- delete() method is available in java.lang package.
- delete() method is used to delete characters in the given range of this sequence.
- In this method the deleting character starts at the given index beg_idx and reaches to the characters ends at the given end_idx ends at the given end_idx-1 and there is a certain condition when beg_idx = end_idx that means in a given range no character exists to delete.
- delete() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- delete() method may throw an exception at the time of assigning an index.
StringIndexOutOfBoundsException - This exception may throw when the beg_idx < 0 or beg_idx is greater than the length of this array sequence or larger than the end_idx.
Syntax:
public StringBuilder delete(int beg_idx , int end_idx);
Parameter(s):
- int beg_idx – represents the starting index to delete.
- int end_idx – represents the ending index to delete (but it does include this index before this index we can include).
Return value:
The return type of this method is StringBuilder, it returns this StringBuilder object.
Example:
// Java program to demonstrate the example
// of StringBuilder delete(int beg_idx , int end_idx)
// method of StringBuilder
public class Delete {
public static void main(String[] args) {
// Creating an StringBuilder object
StringBuilder st_b = new StringBuilder("Java World");
// Display before deletion
System.out.println("st_b = " + st_b);
// By using delete(4,10) method is to delete all the characters
// lies in a given range from index 4 to index 10
st_b = st_b.delete(4, 10);
// Display st_b after deletion
System.out.println("st_b.delete(4,10) = " + st_b);
}
}
Output
st_b = Java World
st_b.delete(4,10) = Java