String immutability in Java - Time & Space Complexity
We want to understand how working with strings in Java affects the time it takes to run code.
Specifically, how does changing strings impact performance as the string size grows?
Analyze the time complexity of the following code snippet.
String s = "";
for (int i = 0; i < n; i++) {
s = s + "a";
}
This code builds a string by adding one character at a time inside a loop.
- Primary operation: Adding a character to the string inside the loop.
- How many times: The loop runs n times, repeating the addition each time.
Each time we add a character, Java creates a new string by copying the old one and adding the new character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copies (1+2+...+10) |
| 100 | About 5,050 copies |
| 1000 | About 500,500 copies |
Pattern observation: The work grows much faster than the input size; it grows roughly like the square of n.
Time Complexity: O(n2)
This means the time to build the string grows very quickly as the string gets longer, because each addition copies the whole string again.
[X] Wrong: "Adding characters to a string in a loop takes time proportional to the number of characters only."
[OK] Correct: Because strings are immutable, each addition copies the entire string so far, making the total work much larger than just n.
Understanding how string immutability affects performance helps you write better code and explain your choices clearly in interviews.
What if we used a StringBuilder instead of adding strings directly? How would the time complexity change?
Practice
String in Java is immutable?Solution
Step 1: Understand the meaning of immutability
Immutability means the object cannot be changed after creation.Step 2: Apply this to Java Strings
Java strings cannot be modified once created; any change creates a new string.Final Answer:
Once created, the string cannot be changed. -> Option AQuick Check:
String immutability = cannot change after creation [OK]
- Thinking strings can be changed directly
- Confusing immutability with constant variables
- Assuming strings change when printed
str?Solution
Step 1: Check syntax for changing characters in strings
Strings are immutable, so direct assignment likestr.charAt(0) = 'A'is invalid.Step 2: Use substring to create a new string
Concatenate "A" with the substring from index 1 to form a new string.Final Answer:
str = "A" + str.substring(1); -> Option CQuick Check:
Use substring + concat to change string [OK]
- Trying to assign directly to string characters
- Using array-like indexing on strings
- Using non-existent methods like replaceChar
String s = "hello"; s.toUpperCase(); System.out.println(s);
Solution
Step 1: Understand that strings are immutable
The methodtoUpperCase()returns a new string but does not change the original strings.Step 2: Check what is printed
Sinceswas not reassigned, printingsoutputs the original string "hello".Final Answer:
hello -> Option BQuick Check:
Original string unchanged = hello [OK]
- Assuming toUpperCase changes original string
- Expecting uppercase output without reassignment
- Confusing method effect with print output
String s = "test"; s.charAt(0) = 'T'; System.out.println(s);
Solution
Step 1: Check usage of charAt()
The methodcharAt()returns a character but cannot be assigned a new value.Step 2: Understand string immutability
Strings cannot be changed by assigning to characters; this causes a compile error.Final Answer:
Cannot assign to charAt() result; strings are immutable. -> Option AQuick Check:
charAt() result is read-only [OK]
- Trying to assign to charAt()
- Thinking strings are mutable
- Ignoring compile errors on assignment
input. Which code correctly does this considering string immutability?Solution
Step 1: Understand replace() returns new string
Thereplace()method returns a new string with replacements but does not change the original.Step 2: Assign the new string back to input
To updateinput, assign the result ofreplace()back to it before printing.Final Answer:
input = input.replace('a', 'b'); System.out.println(input); -> Option DQuick Check:
Assign replace result to variable to update string [OK]
- Calling replace() without assignment
- Trying to assign to charAt() or array elements
- Expecting original string to change automatically
Ready to prove it?
Pass the test and this pattern moves unknown
