VOOZH about

URL: https://www.geeksforgeeks.org/java/stringbuilder-deletecharat-in-java-with-examples/

⇱ StringBuilder deleteCharAt() in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

StringBuilder deleteCharAt() in Java with Examples

Last Updated : 9 Jan, 2026

The deleteCharAt(int index) method of Java's StringBuilder class is used to remove a character at a specified position in a string. It modifies the original StringBuilder, reduces its length by one, and returns the same object.

The method throws a StringIndexOutOfBoundsException if the index is invalid (less than 0 or greater than or equal to the string length). This is useful for efficiently editing strings without creating new string objects.

Example:


Output
Before removal String = WelcomeGeeks
After removal at index 8 = WelcomeGeks

Explanation:

  • A StringBuilder object str is created with the value "WelcomeGeeks".
  • The deleteCharAt(8) method removes the character at index 8 ('e').

Syntax

public StringBuilder deleteCharAt(int index)

  • Parameters: index – the position of the character to remove (0-based).
  • Return Value: Returns the same StringBuilder object after removing the character.

Example 1:This code demonstrates how to use StringBuilder.deleteCharAt() in Java to remove specific characters from a string by index, updating the original string dynamically.


Output
Before removal String = GeeksforGeeks
After removal from index 3 = GeesforGeeks
After removal from index 5 = GeesfrGeeks

Explanation:

  • A StringBuilder object str is initialized with "GeeksforGeeks".
  • deleteCharAt(3) removes the character at index 3 ('k'), and the updated string is printed.
  • deleteCharAt(5) removes the character at index 5 ('f' after the previous removal), and the final string is printed.

Example 2: This code demonstrates how StringBuilder.deleteCharAt() throws a StringIndexOutOfBoundsException when an invalid index is specified, and how to handle it using a try-catch block.


Output
Exception: java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 12

Explanation:

  • A StringBuilder object str is created with the string "evil dead_01".
  • str.deleteCharAt(14): tries to remove a character at index 14, which is beyond the string length.
  • This causes a StringIndexOutOfBoundsException.
  • The try-catch block catches the exception and prints it, preventing the program from crashing.

Related Topics

Comment