String is immutable because there is no way to change the contents of its internal representation, no way to gain a reference to its internal representation, and it cannot be subclassed. This means that no matter what you do to a String, you cannot change its contents.
What methods like toUpperCase()
actually do is return a new String, which has the same contents as the old String. however, the new String is a separate object. references to the initial string will not now point to the new one.
If you wanted to print out the results of toUpperCase()
then do so like the following:
String s="Example";
String upperCase = s.toUpperCase();
System.out.println(upperCase);
EDIT: references vs. objects
A variable in Java is a reference to an object. a recerence is essentially a pointer that tells Java "your object is here", referring to some memory location. However the reference and the object are not the same thing. Lets look at the following as an example
String s = "Test";
String a = s;
String s = "another test"
What I have done here is declared a reference called s
, and set its pointer to a newly created object - in this case a String with value "Test"
. I then declare another reference a
and set it to reference the same object that s
references. Note, that there are two references but only one object.
From there I change the reference s to point to a different object - in this case a String with value "another test"
. This creates a new object, despite the reference being reused. However, the reference a
still points to the original object, which has remained unchanged. if we do println(a)
it will still print "Test"
. This is because the object itself is immutable. Anything that points to it will always return the same value. I can make the references point somewhere else, but cannot change the object.
Think about the variables like entries in a phone book. If I put in an entry for someone and say his last name is "BOB", and someone later comes along and crosses that out and writes "ALICE", this does not suddenly change Bob's gender, or his name. BOB does not spontaneously turn into ALICE because someone rewrote my phone book. It merely changes the value in my phone book, not the actual person. I hope this metaphor helps.