Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the String value changed after String.Replace in Java? [duplicate]

Tags:

java

string

I have a question with this below program

Please see the program below

public class Kiran {

    public static void main(String args[]) {

        String str = "Test";

        str.replace('T', 'B');

        System.out.println("The modified string is now " + str);
    }

}

What i was expecting is that , once i run this program , i should see the putput as Best , but to my surprise the output was Test .

Could anybody please tell me , why is it this way ??

Thanks in advance .

like image 655
Pawan Avatar asked Dec 06 '25 08:12

Pawan


1 Answers

String are immutable in Java, which means you cannot change them. When you invoke the replace method you are actually creating a new String.

You can do the following:

String str = "Test";
str = str.replace('T', 'B');

Which is a reassignment.

like image 56
Edwin Dalorzo Avatar answered Dec 08 '25 21:12

Edwin Dalorzo