Change a single character in a Java StringBuffer object in Java

Java 8Object Oriented ProgrammingProgramming

In order to change a single character in a StringBuffer object in Java, we use the setCharAt() method. The setCharAt() method sets the character at the index specified as a parameter to another character whose value is passed parameter of the setCharAt() method. The method sets a new character sequence with the only change being the character passed as the parameter at the specified index.

Declaration - The java.lang.StringBuffer.setCharAt() method is declared as follows−

public void setCharAt(int index, char ch)

If index is greater than the length of the StringBuffer object or is negative, an IndexOutOfBoundsException is generated.

Let us see a program to change a single character in a StringBuffer object.


 Live Demo

public class Example {
   public static void main(String[] args) {
      StringBuffer sb = new StringBuffer("Hello World");
      sb.setCharAt(7,'a'); // setting character to a at the 7th index


Hello Warld
Published on 03-Jan-2019 16:10:36