Since String
is an immutable object, you can't change its content. Immutable means that once the content of the String
is set, you don't have the ability of changing it in any way. You can always change the reference but never the content itself.
That being said, the String
object doesn't offer any method to violate this principle. There's no setCharAt
and you can't assign a new value to the result of charAt(i)
. Note how some methods that "seem" to change the String
(like replace
) are instead returning a new cloned object with changes on it. For example:
String sample = "Hello World!";
sample.replace('e', '*');
System.out.println(sample);
The above code is not making any changes on sample
, so the result printed on the screen will be Hello World!
. In order to capture the changes made by the replace
method, we need to reassign the sample
variable to the result of replace
:
String sample = "Hello World!";
sample = sample.replace('e', '*');
System.out.println(sample);
In this case we are updating our sample
variable with the new cloned String
returned by replace
. This value will have the changes, so we are going to see H*llo World!
printed out.
Now that you know why you can't change the content of your String
s, let's see what solutions you have.
First and foremost, to keep the exact behavior of your program, the perfect way to go is using a StringBuilder
like @MadProgrammer pointed out before. An over simplistic way of looking at the StringBuilder
class is basically as a mutable String
. With it you can do all kind of replacements and modifications.
Another solution (and not recommended) is to play with the String
to create a new copy every time you want to change a character. This is going to be really cumbersome and offers no advantages over the StringBuilder
solution, so I'm not going to go over the details.
The third solution depends on your requirements and how flexible you can be. If all that you want to do is to replace every occurrence of a certain character in your String
, then your code can be simplified a lot and you can use the replace
method I talked about before. It will be something like:
String theWord = "Here is our testing string";
char letter = 'e';
char changeTo = '*';
String displayWord = theWord.replace(letter, changeTo);
System.out.println("The resulting word is: " + displayWord);
This will output the following result:
The resulting word is: H*r* is our t*sting string
Again, this only works in case your requirements are flexible enough and you can skip the "step by step" approach you are following in your example code.