Card 01/ 09
String Immutability: Why String Methods Return a New String
You call a method to clean up a string, and the string is exactly as it was.
A Java String is immutable: once it exists, nothing can change its characters. Methods such as toUpperCase and strip therefore build a new string and return it, and the original stays as it was. If you do not keep the returned string, the change is lost.
You call a method on a string to clean it up, run the program, and the string is exactly as it was. The method definitely ran; you can see its result in a print statement. Immutable here means exactly that: not "should not be changed", and not "is expensive to change", but that no operation anywhere alters the characters of an existing string.
String greeting = "hello";
greeting.toUpperCase();
System.out.println(greeting);
System.out.println(greeting.toUpperCase());hello
HELLOLine 2 did produce "HELLO". It built a second string and returned it, and nothing caught the return value, so it was thrown away immediately. greeting still points at the string it always pointed at.
The fix is one assignment: greeting = greeting.toUpperCase(); points greeting at the new string. The old string is not changed even then; the variable just stops pointing at it, and it is cleaned up once nothing refers to it.
So any String method whose result you do not assign to something has done nothing you can observe. That one sentence explains most of the surprising behaviour in this topic, including why comparing strings with == misleads and why building one in a loop is expensive.
← → move through sections and cards