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.

The same content can sit in two separate places in memory.
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);    // DANA

Why 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 operationChanges the originalReturns
To capitalsNoA new string
Replace a characterNoA new string
Cut a partNoA new string

Example 1 — why the third line does nothing

  1. The operation returns a new string.
  2. No one kept what was returned.
  3. And the original was untouched.

Example 2 — what unchangeability buys

  1. One can pass without copying.
  2. No one will change it underfoot.
  3. And the language can share, saving memory.
Lines 3 and 6 call exactly the same operation. The only difference is who receives what was returned.