StringProblem 4 of 43
Why strings are immutable in Java
Problem Statement
Why are strings immutable in Java, and what are the practical implications for coding interviews?
Example:
- Input operation:
s = s + "x"repeatedntimes - 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
- Start with an empty
String - Append one character in a loop using
+ - Each append creates a new
String - 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
- Create a
StringBuilder - Append in loop using
append() - Convert to
StringusingtoString() - 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
- Security: class names, file paths, URLs, and credentials cannot be altered after validation.
- String Pool: literals can be safely shared because value never changes.
- Thread Safety: immutable objects are naturally safe to share across threads.
- Hashing Stability: cached
hashCode()makesHashMaplookup efficient and reliable.
Interview Takeaways
- Java
Stringis immutable by design. - Prefer
StringBuilderfor repeated updates. - Use
Stringfor read-mostly values, map keys, and APIs.