Why Strings Are Immutable (Interview Concept)

Interview Concept: Why Strings Are Immutable

In Java and Python, a string cannot be changed after it is created; every operation that looks like a modification actually produces a new string object. This is a common interview question because it explains real performance behavior, not just trivia.

Example

s = "hello"
s = s + " world"  # creates a NEW string object; the original "hello" is unchanged
String s = "hello";
s = s.concat(" world"); // returns a NEW String; the original object is untouched

Why immutability exists

  • Safety for shared use. Strings are used as dictionary/hash map keys, cached, and passed around freely; if they could change in place, every place holding a reference would suddenly see different data.
  • Thread safety. An immutable object can be shared across threads with no risk of one thread changing it while another reads it.
  • Caching and interning. Since a string never changes, identical string literals can safely share the same memory (string interning in Java, similar behavior in Python for short strings).

The performance cost this creates

Building a string with repeated concatenation in a loop:

  result = ""
  for word in many_words:
      result += word   # each += creates a brand new string,
                        # copying everything built so far

For n words, this becomes O(n^2) total work, because each
concatenation re-copies the growing result.

The fix

Use a mutable buffer (Python's list + "".join(...), or Java's StringBuilder) to accumulate pieces, and build the final string once at the end, instead of once per concatenation.

Complexity

Naive repeated concatenation: O(n²) for n operations, since each one copies the string built so far. Using a mutable buffer and joining once: O(n), since each piece is appended once and copied exactly once at the end.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.