Mutable strings can be changed in place (like a whiteboard). Immutable strings cannot be modified — any change creates a new string (like carving a new stone tablet).
Mutable = whiteboard: erase 'H' and write 'J' instantly. Immutable = stone tablet: can't change it, must carve a whole new tablet. The old one stays untouched.
In Mutable strings, we modify the memory directly.
C, C++, Ruby
You can erase 'H' and write 'J' instantly.
Same memory address, modified in place
Java, Python, JS
You can't change it. You must carve a whole new tablet.
New memory address, old string preserved
1// Mutable (C++)2char str[] = "Cat";3str[0] = 'B'; // Changes in place4// str now contains "Bat" at same address56// Immutable (Java)7String str = "Cat";8str = str.replace('C', 'B'); // Creates NEW string9// Original "Cat" still exists in memory10// str now points to new "Bat" string1112// For many modifications, use StringBuilder:13StringBuilder sb = new StringBuilder("Cat");14sb.setCharAt(0, 'B'); // More efficient15String result = sb.toString();
This concept trips up many programmers. Let's understand it clearly.
Mutable Strings (C/C++, Ruby)
Think of a whiteboard. You can erase and rewrite:
Immutable Strings (Java, Python, JavaScript)
Think of a stone tablet. You can't change it:
Why Immutability?
Performance Implications
The Memory View
Mutable: One string, one address, changes in place
Immutable: Each modification creates a new string at a new address
This is the biggest difference between programming languages! C/C++ use mutable strings, while Java/Python/JavaScript use immutable strings. Understanding this prevents bugs and helps you write efficient code.
"What happens when you modify an immutable string?"
A new string is created in memory, and the variable points to the new address. The original string remains unchanged at its original memory location.