Card 02/ 09
String Immutability Example: Upper-Casing a Name
The result is kept, both strings are printed, and the original has not moved.
Keeping the result of a String method gives you a second string and leaves the first untouched. A name, a method call whose result is assigned, and both strings printed afterwards:
String name = "Ada Lovelace";
String shouted = name.toUpperCase();
System.out.println(name);
System.out.println(shouted);Ada Lovelace
ADA LOVELACETwo strings now exist. name points at the one it was given; shouted points at the one the method built. The method did not consult name about whether it minded, and it could not have changed it if it had.
If name could have been changed, a second part of the program holding the same name, such as a list of customers, would suddenly be shouting too. Immutability is what makes it safe to hand strings around freely.
Notice the shape of line 2: a String variable on the left of the assignment. Every method that transforms text has that shape, because every one of them hands back something new.
← → move through sections and cards