In this guide, we will discuss the Java StringBuffer deleteCharAt() method with examples.
Syntax of deleteCharAt() Method:
sb.deleteCharAt(4); //deletes char present at index 4
Here sb is an instance of StringBuffer class.
deleteCharAt() Description
public StringBuffer deleteCharAt(int index): This method deletes the character present at the specified index. The StringBuffer instance returned by this method is one char short in length.
deleteCharAt() Parameters
It takes a single parameter:
- index: An integer value that represents the index (position) of a character in the sequence. The character specified by this index is deleted.
deleteCharAt() Return Value
- Returns an instance of StringBuffer after deleting the specified character.
It throws StringIndexOutOfBoundsException, if any of the following condition occurs:
- If
index < 0 - If
index >= sb.length()
Example 1: Delete char at specified index
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Welcome");
System.out.println(sb);
sb.deleteCharAt(2); //delete 3rd char
System.out.println(sb);
sb.deleteCharAt(3); //delete 4th char
System.out.println(sb);
}
}
Output:

Example 2: Delete First and Last char of the sequence
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Cool");
System.out.println("StringBuffer before delete: "+sb);
//deleting first char
sb.deleteCharAt(0);
//deleting last char
sb.deleteCharAt(sb.length()-1);
//print Sequence
System.out.println("StringBuffer after delete: "+sb);
}
}
Output:

Example 3: Delete Last two Characters
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
System.out.println("StringBuffer before delete: "+sb);
//deleting last two characters
sb.deleteCharAt(sb.length()-1);
sb.deleteCharAt(sb.length()-1);
//print Sequence
System.out.println("StringBuffer after delete: "+sb);
}
}
Output:

Example 4: Delete First two characters
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
System.out.println("StringBuffer before delete: "+sb);
//deleting first two characters
sb.deleteCharAt(0);
sb.deleteCharAt(0);
//print Sequence
System.out.println("StringBuffer after delete: "+sb);
}
}
Output:

Example 5: If specified index is negative
public class JavaExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
sb.deleteCharAt(-1);
System.out.println(sb);
}
}
Output:
