Why String Is Immutable in Java
Beginners often write name.toUpperCase(); and are surprised that name hasn't changed. That's not a bug: a String can never change once it's created. Every method that seems to modify a string, like toUpperCase, replace or trim, actually builds and returns a new string, and leaves the original exactly as it was. This lesson shows what that looks like and, more importantly, why Java was designed this way.
What "Immutable" Looks Like
public class Immutable {
public static void main(String[] args) {
String name = "navika";
name.toUpperCase();
System.out.println(name);
String upper = name.toUpperCase();
System.out.println(name + " " + upper);
name = name.toUpperCase();
System.out.println(name);
}
}navika
navika NAVIKA
NAVIKAHow it works
name.toUpperCase();creates the new string"NAVIKA"and then throws it away, because nothing stores it.namestill says"navika".- Storing the result in
upperkeeps the new string. The original is still unchanged. name = name.toUpperCase();makes the variable point to the new string. The old"navika"object itself never changed; the variable simply moved.
Why Java Made Strings Immutable
This was a deliberate design choice, and each reason is something you rely on every day.
| Reason | What would go wrong if strings could change |
|---|---|
| 1. The String pool can share objects | One part of the program changing a pooled "INR" to "USD" would change it for every other part using that literal |
| 2. Security | A method checks that a file name is "report.txt", then a second thread changes it to a system file before it's opened |
3. Safe as HashMap keys | A key's hash code is calculated when it's stored; if the text changed, the map could never find it again |
| 4. Thread safety for free | Many threads can read the same string at once without any locking, because none of them can change it |
| 5. Hash code caching | String remembers its hash code after the first calculation, which makes repeated HashMap lookups faster |
Reasons 1 and 3 show the core idea: when many places share an object, the only way to make sharing safe is to make sure nobody can change it.
How Java Enforces It
Looking at the String class itself shows the rules from "How to Create an Immutable Class in Java":
- The class is
final, so nobody can write a subclass that adds a setter. - Its character data is a
private finalarray that's never handed out; methods liketoCharArray()return a copy. - No method changes that array after construction.
Common Mistakes
Calling a string method without using the result. s.trim(); alone does nothing useful; write s = s.trim();.
Building text with + in a big loop. Each step creates a new string; use StringBuilder.
Thinking final String s and "immutable String" mean the same. final stops the variable being reassigned; immutability means the object can't change.
Interview Corner
Why is String immutable in Java?
So that strings can be shared safely. Immutability allows the String pool to reuse one object for identical literals, keeps security-sensitive values such as file paths and class names from being changed after they're checked, makes strings reliable HashMap keys whose hash codes never change, makes them thread-safe without synchronization, and lets String cache its hash code.
If String is immutable, how does s = s + "x" work?
The + creates a brand-new string containing the combined text, and the assignment makes the variable s point to it. The original string object is unchanged; if nothing else refers to it, it becomes eligible for garbage collection.
Practice
- Easy: Write
String city = " pune ";, then make it"PUNE"with no spaces. Print it before and after each step to see which calls change the variable. - Harder: Write a method
static void shout(String s) { s = s.toUpperCase(); }. Call it with a string and print the string afterwards. Explain the result.
Key Takeaways
Was this tutorial helpful?