How can I change a character inside a string in Java?

Hello I decided to change from C++ to Java and on my first problem I needed to manipulate a String by changing a characted inside it…

However it seems myString[x]=’(some char)’ doesn’t work here and I couldn’t find any method that could change a character either…

Could it be that this is impossible to do in Java?!

Thanks in advance!

1 Like

String class is immutable in Java (once created, you cannot modify it). You have to use something else, for example array of characters (see String.toCharArray()) or use other class that is not immutable f.e. StringBuilder.

  1. String is immutable in java. We can not change character using any built in java string method. You have to use another string to achieve this.

String myName = “francis”;

String newName = myName.substring(0,4)+‘x’+myName.substring(5);

  1. The second way to achieve this is, StringBuilder

StringBuilder myName = new StringBuilder(“domanokz”);

myName.setCharAt(4, ‘x’);**

You can use a replace method, to replace the specified character in the String, but take care all the specified character appearing will be replaced.

String s=new String(“Code”);

Output: Coda