![]() |
VOOZH | about |
The setCharAt() method of the StringBuilder class is used to replace a character at a specified index with a new character. This method modifies the existing StringBuilder object and does not create a new string.It does not return any value.
JOva
Explanation: The character at index 1 is replaced with 'O' & original StringBuilder object is modified directly.
public void setCharAt(int index, char ch)
Parameters:
Returns: returns nothing.
Exception: If the index is negative, greater than length() then IndexOutOfBoundsException.
Example 1: This code shows how setCharAt() replaces a character at a specific index in a StringBuilder.
String = WelcomeGeeks After setCharAt() String = WeLcomeGeeks
Explanation:
Example 2: This replaces a character in the middle of a sentence using setCharAt().
String = Tony Stark will die After setCharAt() String = Tony Star1 will die
Explanation:
Example 3: When an invalid (negative) index is provided, behavior of setCharAt() changes.
Output:
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)
Explanation: