Immutable String

An immutable string is a string object whose value cannot be modified after it is created.

Languages: Java, Python, C#, JavaScript, Go. Counter-examples: C strings (char arrays), StringBuilder (Java).

        graph LR
  Center["Immutable String"]:::main
  classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
  classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
  classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
  classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
  linkStyle default stroke:#4b5563,stroke-width:2px;

      

🧒 Explain Like I'm 5

Imagine you have a name tag that is glued on with super-glue. You can't change your name on that tag. If you want a different name, you have to throw the tag away and get a whole new one. This keeps things simple because the teacher always knows exactly who you are without worrying your tag changed in the middle of [class](/en/terms/class).

🤓 Expert Deep Dive

Technically, string immutability provides three critical benefits: 1. Thread Safety (no synchronization needed). 2. String Interning (reusing the same memory address for identical literals to save space). 3. Hash Code Stability (since the content never changes, the hash code can be cached). This is vital for using strings as keys in HashMaps or Dictionaries. If a string were mutable, changing it after it was placed in a map would break the map's lookup logic, leading to subtle and dangerous bugs.

📚 Sources