java.lang.StringBuffer setCharAt(int index,char ch)

Description :

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

This method replaces the character of the buffer with character ch method argument at specified index.

Method Syntax :

public void setCharAt(int index,char ch)

Parameter Input :

DataType Parameter Description
int index the index of the character on the character sequence to be replaced
char ch the character that will be replaced on the buffer contents

Compatibility Version :

Requires Java 1.0 and up

Java Code Example :

This java example source code demonstrates the use of setCharAt(int index,char ch) method of StringBuffer class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use setCharAt(int index,char ch) method to replace the character at index 15 with character ‘X’.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * setCharAt(int index,char ch) method of StringBuffer class
 */

public class StringBufferSetCharAt {

	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 = 15;
		char ch = 'X';
		
		// change the character at index 15
		sb.setCharAt(index, ch);
		System.out.println("New Contents of Buffer:"+sb);
		
		


	}
}

Sample Output :

Running the above example source code will give the following output

setCharAt(int index,char ch)

setCharAt(int index,char ch)

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 :