Grade 11 Computer Science · Strings and equality
A string never changes
Why every operation on it produces a new string.
A line that ran and did nothing
You call the operation that turns a name to capitals, print the name — and it is still in small letters. There is no error, and the operation worked exactly as it should. So where did the result vanish to, and why does the language deliberately not allow the string itself to change?
A string looks like the simplest type in the language, and it is the one that catches most beginners. The reason is one property visible nowhere in the code: once a string is created, it cannot be changed. At all. Ever.
String name = "dana";
name.toUpperCase(); // returns "DANA" — and it is thrown away
System.out.println(name); // dana — unchanged
name = name.toUpperCase(); // now the name points at the new string
System.out.println(name); // DANAWhy it was built this way
This property is no accidental limitation — it is a choice buying two things. The first: a string is safe to pass anywhere without fear that someone will change it under your feet, so it never needs copying. The second: since no one can change it, the language can share identical strings between names and save memory. Both those gains are exactly the ones you learned about in the lesson on unchangeable values.
| The operation | Changes the original | Returns |
|---|---|---|
| To capitals | No | A new string |
| Replace a character | No | A new string |
| Cut a part | No | A new string |
Example 1 — why the third line does nothing
- The operation returns a new string.
- No one kept what was returned.
- And the original was untouched.
Example 2 — what unchangeability buys
- One can pass without copying.
- No one will change it underfoot.
- And the language can share, saving memory.