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.
class GFG {
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Java");
sb.setCharAt(1, 'O');
System.out.println(sb);
}
}
Output
JOva
Explanation: The character at index 1 is replaced with 'O' & original StringBuilder object is modified directly.
Syntax
public void setCharAt(int index, char ch)
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.
Returns: returns nothing.
Exception: If the index is negative, greater than length() then IndexOutOfBoundsException.
Examples of setCharAt()
Example 1: This code shows how setCharAt() replaces a character at a specific index in a StringBuilder.
class GFG{
public static void main(String[] args){
StringBuilder str = new StringBuilder("WelcomeGeeks");
System.out.println("String = " + str.toString());
str.setCharAt(2, 'L');
System.out.println("After setCharAt() String = " + str.toString());
}
}
Output
String = WelcomeGeeks After setCharAt() String = WeLcomeGeeks
Explanation:
- str.setCharAt(2, 'L'): targets index 2 of the StringBuilder object str.
- The character at that position is replaced with 'L', modifying "WelcomeGeeks" to "WeLcomeGeeks" in place.
Example 2: This replaces a character in the middle of a sentence using setCharAt().
class GFG{
public static void main(String[] args){
StringBuilder str = new StringBuilder("Tony Stark will die");
System.out.println("String = "+ str.toString());
str.setCharAt(9, '1');
System.out.println("After setCharAt() String = " + str.toString());
}
}
Output
String = Tony Stark will die After setCharAt() String = Tony Star1 will die
Explanation:
- str.setCharAt(9, '1'): updates the character at index 9 in the StringBuilder object str.
- The original sequence is modified in place, changing "Tony Stark will die" to "Tony Star1 will die".
Example 3: When an invalid (negative) index is provided, behavior of setCharAt() changes.
class GFG{
public static void main(String[] args){
StringBuilder str= new StringBuilder("Tony Stark");
try {
str.setCharAt(-15, 'A');
}
catch (Exception e) {
e.printStackTrace();
}
}
}
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:
- str.setCharAt(-15, 'A'): attempts to access an index outside the valid range of the StringBuilder.
- Since negative indexes are not allowed, the JVM throws a StringIndexOutOfBoundsException at runtime.