VOOZH about

URL: https://www.geeksforgeeks.org/java/replace-a-character-at-a-specific-index-in-a-string-in-java/

⇱ Replace a character at a specific index in a String in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Replace a character at a specific index in a String in Java

Last Updated : 11 Jul, 2025

 In Java, here we are given a string, the task is to replace a character at a specific index in this string.

Examples of Replacing Characters in a String

Input: String = "Geeks Gor Geeks", index = 6, ch = 'F'
Output: "Geeks For Geeks."
Input: String = "Geeks", index = 0, ch = 'g'
Output: "geeks"

Methods to Replace Character in a String at Specific Index

There are certain methods to replace characters in String are mentioned below:

  1. Using String Class
  2. Using StringBuilder
  3. Using StringBuffer

1. Using String Class

There is no predefined method in String Class to replace a specific character in a String, as of now. However, this can be achieved indirectly by constructing a new String with 2 different substrings, one from the beginning till the specific index - 1, the new character at the specific index, and the other from the index + 1 till the end.

Below is the implementation of the above approach: 


Output
Original String = Geeks Gor Geeks
Modified String = Geeks For Geeks

2. Using StringBuilder

Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a character at a specific index - setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.

Below is the implementation of the above approach: 


Output
Original String = Geeks Gor Geeks
Modified String = Geeks For Geeks

3. Using StringBuffer

Like StringBuilder, the StringBuffer class has a predefined method for this purpose - setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter. StringBuffer is thread-safe and can be used in a multi-threaded environment. StringBuilder is faster when compared to StringBuffer, but is not thread-safe.

Below is the implementation of the above approach:


Output
Original String = Geeks Gor Geeks
Modified String = Geeks For Geeks
Comment