How Can A Character At A Specific Index In A String Be Replaced In Java?

In Java, strings are immutable, meaning that you cannot modify them directly. However, you can use the StringBuilder class to replace characters at specific indices in a string. Here’s an example:

String originalString = "Hello World";
int indexToReplace = 6;  // Index of 'W' to be replaced
char newChar = 'J';

StringBuilder stringBuilder = new StringBuilder(originalString);
stringBuilder.setCharAt(indexToReplace, newChar);

String modifiedString = stringBuilder.toString();


Hello Jorld

In the example above, we create a StringBuilder object and initialize it with the originalString. Then, we use the setCharAt method of the StringBuilder class to replace the character at indexToReplace with newChar. Finally, we convert the modified StringBuilder back to a string using the toString method and print it.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!