VOOZH about

URL: https://www.geeksforgeeks.org/java/stringbuilder-setcharat-in-java-with-examples/

⇱ StringBuilder setCharAt() in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

StringBuilder setCharAt() in Java with Examples

Last Updated : 19 Dec, 2025

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.


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.


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().


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.

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.
Comment
Article Tags: