Card 02/ 09

ExampleDifficulty: Beginner1 min

Upper-Casing a Name and Watching the Original Not Change

A name, a method call whose result is kept, and both strings printed afterwards. Nothing goes wrong here, and it is worth watching the version that works before the version that does not.

java
String name = "Ada Lovelace";
String shouted = name.toUpperCase();

System.out.println(name);
System.out.println(shouted);
text
Ada Lovelace
ADA LOVELACE

Two 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.

What to notice is 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.