14 / 19

Why are Strings immutable in Java/C#? What are the benefits?

Difficulty: 3/10

String Immutability

Immutable strings cannot be changed after they are created. In Java this is a fundamental property of String. In modern .NET, System.String is also immutable. If a modification is requested, a new string is created rather than modifying the original object.

  1. 1

    String interning and pooling become safe because shared strings cannot be changed by one consumer.

  2. 2

    Immutability makes strings easier to reason about in concurrent programs.

  3. 3

    Hash codes can be safely cached because the contents cannot change.

  4. 4

    Strings used as map keys remain stable after insertion.

  5. 5

    Immutability reduces certain classes of accidental state-sharing bugs.

  6. 6

    Repeated concatenation can still be inefficient, so StringBuilder or equivalent builders should be used for many modifications.

Follow-up Questions

  • How does string interning work?
  • Why is StringBuilder more efficient for repeated concatenation?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.