java.lang.StringBuffer deleteCharAt(int index)

Description :

This java tutorial shows how to use the deleteCharAt(int index) method of StringBuffer class under java.lang package.

This method removes the character at the specified method argument index of the contents of the stringbuffer.

Method Syntax :

public StringBuffer deleteCharAt(int index)

Parameter Input :

DataType Parameter Description
int index the position of the character we want to remove on the character sequence.

Compatibility Version :

Requires Java 1.0 and up

Java Code Example :

This java example source code demonstrates the use of deleteCharAt(int index)  method of StringBuffer class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use deleteCharAt method to delete the character of the stringbuffer on index 5.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * deleteCharAt(int index) method of StringBuffer class
 */

public class StringBufferDeleteCharAt {

	public static void main(String[] args) {

		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer("javatutorialhq.com");
		System.out.println("Contents of buffer:" + sb);

		int index = 5;
		
		
		// delete the character at index 5
		sb.deleteCharAt(index);
		System.out.println("New Contents of Buffer:"+sb);
		
		


	}
}

Sample Output :

Running the above example source code will give the following output

deleteCharAt(int index) method example

deleteCharAt(int index) method example

Exception Scenario :

IndexOutOfBoundsException

The above exception will be if the following condition has been met:

  • if index is negative or greater than or equal to length().

Suggested Reading List :

References :