Change a Single Character in a Java StringBuffer Object



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.

Example

 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
      System.out.println(sb);
   }
}

Output

Hello Warld
Updated on: 2020-06-26T15:06:45+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements