Java: StringBuilder deleteCharAt() method

In this article, we will discuss StringBuilder’s deleteCharAt() method which deletes a char value at a specified index-position

 

deleteCharAt() method:

  • This method deletes single character from the invoking StringBuilder object at the specified index-position

 

Method Signature:

public StringBuilder deleteCharAt(int index);

 

Returns:

  • Returns StringBuilder object after deleting single character at the specified index-position

 

Throws:

StringIndexOutOfBoundsException, if index value passed falls out of range i.e.;

  • if specified index value negative (<0)
  • if specified index value is greater than length()

 

Examples on deleteCharAt() method:

To delete single char value from the invoking StringBuilder object at the specified index-position

StringBuilderDeleteCharAtMethod.java

package in.bench.resources.stringbuilder.methods;

public class StringBuilderDeleteCharAtMethod {

	public static void main(String[] args) {

		// StringBuilder - 1
		StringBuilder sb1 = new StringBuilder("Google.com"); 

		// removes single character at specified index-position
		sb1.deleteCharAt(5);

		// print to console
		System.out.println("1. after deleting single char from StringBuilder "
				+ "at 5th index : " + sb1);


		// StringBuilder - 2
		StringBuilder sb2 = new StringBuilder("Oracle.com"); 

		// removes single character at specified index-position
		sb2.deleteCharAt(2);

		// print to console
		System.out.println("2. after deleting single char from StringBuilder "
				+ "at 2nd index : " + sb2);
	}
}

Output:

1. after deleting single char from StringBuilder at 5th index : Googl.com
2. after deleting single char from StringBuilder at 2nd index : Orcle.com

 

References:

https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

Happy Coding !!
Happy Learning !!

Java: StringBuilder ensureCapacity() method
Java: StringBuilder delete() method