StringProblem 4 of 43

Why strings are immutable in Java

Brute Force
Time: O(n^2)
Space: O(n^2)
Optimal
Time: O(n)
Space: O(n)

Problem Statement

Why are strings immutable in Java, and what are the practical implications for coding interviews?

Example:

  • Input operation: s = s + "x" repeated n times
  • Observation: String objects are not modified in-place

Approach 1: Brute Force (Repeated String Concatenation)

Intuition

String is immutable, so every concatenation creates a new object and copies previous content.

Algorithm

  1. Start with an empty String
  2. Append one character in a loop using +
  3. Each append creates a new String
  4. Previous object becomes garbage
java
public class Solution {
    public String buildStringBrute(int n) {
        String s = "";
        for (int i = 0; i < n; i++) {
            s = s + "a";
        }
        return s;
    }
}

Complexity Analysis

  • Time Complexity: O(n^2) - Copy cost grows with string length at each step
  • Space Complexity: O(n^2) - Many intermediate immutable objects are created

Approach 2: Optimal (StringBuilder + Convert Once)

Intuition

Use a mutable buffer (StringBuilder) during construction, and create final immutable String only once.

Algorithm

  1. Create a StringBuilder
  2. Append in loop using append()
  3. Convert to String using toString()
  4. Return final immutable result
java
public class Solution {
    public String buildStringOptimal(int n) {
        StringBuilder sb = new StringBuilder(n);
        for (int i = 0; i < n; i++) {
            sb.append('a');
        }
        return sb.toString();
    }
}

Complexity Analysis

  • Time Complexity: O(n) - Each append is amortized O(1)
  • Space Complexity: O(n) - Buffer plus final immutable string

Why Java Keeps String Immutable

  1. Security: class names, file paths, URLs, and credentials cannot be altered after validation.
  2. String Pool: literals can be safely shared because value never changes.
  3. Thread Safety: immutable objects are naturally safe to share across threads.
  4. Hashing Stability: cached hashCode() makes HashMap lookup efficient and reliable.

Interview Takeaways

  1. Java String is immutable by design.
  2. Prefer StringBuilder for repeated updates.
  3. Use String for read-mostly values, map keys, and APIs.