String.replace() isn't working like I expect

132 views Asked by At

I am not understanding how to use the String.replace() method. Here is the code:

    CharSequence oldNumber = "0";
    CharSequence newNumber = "1";
    String example = "folderName_0";
    System.out.println("example = " + example);
    example.replace(oldNumber, newNumber);
    System.out.println("example.replace(oldNumber, newNumber);");
    System.out.println("example = " + example);

And it's outputting:

example = folderName_0
example.replace(oldNumber, newNumber);
example = folderName_0 // <=== How do I make this folderName_1???
3

There are 3 answers

0
rgettman On BEST ANSWER

The replace method isn't changing the contents of your string; Strings are immutable. It's returning a new string that contains the changed contents, but you've ignored the returned value. Change

example.replace(oldNumber, newNumber);

with

example = example.replace(oldNumber, newNumber);
0
M A On

Strings are immutable. You need to re-assign the returned value of replace to the variable:

example = example.replace(oldNumber, newNumber);
0
Moni On

String is a immutable object, when you are trying to change your string with the help of this code - example.replace(oldNumber,newNumber); it changed your string but it will be a new string and you are not holding that new string into any variable. Either you can hold this new string into a new variable, if you want to use your old string value later in your code like -

String changedValue = example.replace(oldNumber,newNumber);

or you can store in the existing string if you are not going to use your old string value later like -

example = example.replace(oldNumber,newNumber);