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 invoking StringBuilder object at specified index-position

Method Signature:

public StringBuilder deleteCharAt(int index);

Returns:

  • Returns StringBuilder object after deleting single character at 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 invoking StringBuilder object at specified index-position

StringBuilderDeleteCharAtMethod.java

package in.bench.resources.string.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:

 

Happy Coding !!
Happy Learning !!

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