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

Description

On this document we will be showing a java example on how to use the setCharAt(int index,char ch) method of StringBuilder Class. Basically the setCharAt() method behaves in such a way that the character at the specified index is set to ch. This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.

Notes:

  • An IndexOutOfBoundsException will be thrown by the setCharAt() method if the index is negative or greater than or equal to length().

Method Syntax

public void setCharAt(int index,char ch)

Method Argument

Data Type Parameter Description
int index index of the char to be set.
char ch the new character.

Method Returns

The setCharAt(int index,char ch) method returns void.

Compatibility

Requires Java 1.5 and up

Java StringBuilder setCharAt(int index,char ch) Example

Below is a java code demonstrates the use of setCharAt() method of StringBuilder class. The example presented might be simple however it shows the behavior of the setCharAt() method.

package com.javatutorialhq.java.examples;

/*
 * A java example source code to demonstrate
 * the use of setCharAt() method of StringBuilder class
 */

public class StringBuilderSetCharAtExample {

	public static void main(String[] args) {

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

		int index = 15;
		char ch = 'X';

		// change the character at index 15
		sb.setCharAt(index, ch);
		System.out.println("New Contents of StringBuilder:" + sb);
	}
}

The java example source code above, demonstrates the use of setCharAt(int index,char ch) method of StringBuilder 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’.

Sample Output

Below is the sample output when you run the above example.

StringBuilder setCharAt() example output