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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With