Why String Is Immutable in Java

Naveen AnamaneniUpdated · 5 min read

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

Methods return new strings; the original never changes
Immutable.java▶ Try it
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);
    }
}
Output
navika
navika NAVIKA
NAVIKA

How it works

  1. name.toUpperCase(); creates the new string "NAVIKA" and then throws it away, because nothing stores it. name still says "navika".
  2. Storing the result in upper keeps the new string. The original is still unchanged.
  3. 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.

ReasonWhat would go wrong if strings could change
1. The String pool can share objectsOne part of the program changing a pooled "INR" to "USD" would change it for every other part using that literal
2. SecurityA 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 keysA 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 freeMany threads can read the same string at once without any locking, because none of them can change it
5. Hash code cachingString 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 final array that's never handed out; methods like toCharArray() 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

  1. 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.
  2. 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.

Quick check: Immutability

4 questions
1String s = "java"; s.toUpperCase(); System.out.println(s); prints:
2Which reason for immutability involves the String pool?
3Why are immutable strings good HashMap keys?
4What should you use to change text many times in a loop?

Key Takeaways

Was this tutorial helpful?

Lesson 189 of 482