Java .deleteCharAt()

StevenSwiniarski's avatar
Published Aug 22, 2022
Contribute to Docs

The .deleteCharAt() method removes the character at the specified index from the contents of a StringBuilder and returns the modified object.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

myStringbuilder.deleteCharAt(index);

The int argument index specifies the zero-based index of the character to delete. The sequence is shortened by one character. If index is negative or greater than the length of the sequence, a StringIndexOutOfBoundsException is thrown.

Example

The following example creates a StringBuilder with a specified String then uses the .deleteCharAt() method to change its contents:

import java.util.*;
public class Example {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Hello World!");
System.out.println(str.toString());
str.deleteCharAt(11);
System.out.println(str.toString());
}
}

This produces the following output:

Hello World!
Hello World

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours