This post will discuss how to replace a character at a specific index in a Java String.

The string is an immutable class in Java. That means we cannot make any change in the String object. The only feasible solution is to create a new String object with the replaced character. There are several ways to replace a character at a specific index in a string:

1. Using substring() method

We can use String.substring(int, int) method to partition the string into two halves consisting of substring before and after the character to be replaced. Once we have isolated the character to be replaced, we can use the concatenation operator to build the final string, as shown below:

Download  Run Code

Output:

Techie_Delight

2. Using StringBuilder

The recommended solution is to use mutable class StringBuilder to efficiently replace a character at a specific index in a string in Java. Alternatively, we can also use a slower StringBuffer class if thread safety is required.

Download  Run Code

Output:

Techie_Delight

3. Using toCharArray() method

Another plausible way of replacing character at the specified index in a string is using a character array that can be modified easily. The idea is to convert the given string to a character array using its toCharArray() method and then replace the character at the given index in the character array. Finally, convert the character array back into a string using String.valueOf(char[]) method.

Download  Run Code

Output:

Techie_Delight

4. Using Reflection

We have seen that we cannot make any change in the String object as string is immutable in Java. However, there is a way to modify a string using reflection. Reflection in Java allows code to perform illegal operations such as accessing and manipulating private fields and methods.

We know that string internally uses a character array that is final and private to the class. Although not recommended, reflection can easily modify that private character array.

Download Code

Output:

Techie_Delight

That’s all about replacing a character at a specific index in a Java String.