0

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???
0

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

example = example.replace(oldNumber, newNumber);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.