Card 01/ 09

ConceptDifficulty: Beginner1 min

Why Changing a String Gives You a Different String

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.

A Java String cannot be changed after it is made. Not "should not" and not "is expensive to": there is no operation anywhere that alters the characters of an existing string.

java
String greeting = "hello";
greeting.toUpperCase();

System.out.println(greeting);
System.out.println(greeting.toUpperCase());
text
hello
HELLO

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

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.