Immutability of Strings
means you cannot modify any String
object.
Notice the above example for the method toLowerCase
. This method returns a new String
, which is the lower case version of the object that invoked the method.
String greeting = "Hi World!";
greeting.toLowerCase();
System.out.println(greeting);
Run Output:
Hi World!
The object greeting did not change. To change the value of greeting, you need to assign the return value of the method to the object greeting.
greeting = greeting.toLowerCase();
System.out.println(greeting);
Run Output:
hi world!