StringBuilder setCharAt() in Java with Examples
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBUilder object.
public void setCharAt(int index, char ch)
This method accepts two parameters:
- index – Integer type value which refers to the index of character you want to set.
- ch – Character type value which refers to the new char.
This method returns nothing.
If the index is negative, greater than length() then IndexOutOfBoundsException.
Below programs illustrate the java.lang.StringBuilder.setCharAt() method:
String = WelcomeGeeks After setCharAt() String = WeLcomeGeeks
String = Tony Stark will die After setCharAt() String = Tony Star1 will die
Example 3: When negative index is passed:
java.lang.StringIndexOutOfBoundsException: String index out of range: -15 at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:407) at java.lang.StringBuilder.setCharAt(StringBuilder.java:76) at GFG.main(File.java:16)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.