Skip to lesson

String Immutability, the String Pool and == vs equals

In almost every Java interview someone asks, "Why is String immutable?" and then shows a == puzzle. The interviewer is checking whether you know the reasons, the string pool and why equals is the safe choice.

Recap: String is immutable and final

Immutable means an object cannot change after it is created. A String is immutable: methods such as toUpperCase, trim and concat return a new string and leave the original as it was.

Start with the smallest fact. This program calls String methods and shows that the original text never changes unless you store the result.

Example 1 · Every change creates a new string

ImmutableDemo.javaJava
public class ImmutableDemo {    public static void main(String[] args) {        String city = "pune";        city.toUpperCase();        city.concat(" 411001");        System.out.println(city);
        String upper = city.toUpperCase();        System.out.println(upper);        System.out.println(city);
        city = city + " 411001";        System.out.println(city);    }}
Output
pune
PUNE
pune
pune 411001

What this code does

  • The first two calls return new strings that nobody stores, so city still prints pune.
  • upper holds the new object while city is unchanged. city = city + ... does not modify the old string either: it points city at a brand-new one.

String is also final, so no subclass can break the rule. It is a class, not a primitive, but literals and + get special support. Remember: every "change" creates a new object, == compares references and equals compares text.

Revise: What is a String (opens in a new tab) and Immutable objects (opens in a new tab).

Model answer: why String is immutable

Interviewers expect four reasons. This program shows the first one: sharing is only safe when nobody can change the shared object.

Example 2 · Why sharing needs immutability

SharingDemo.javaJava
public class SharingDemo {    public static void main(String[] args) {        StringBuilder roomA = new StringBuilder("Block-B");        StringBuilder roomB = roomA;          // two references, one mutable object        roomB.append("-204");        System.out.println("Mutable:   " + roomA);
        String hostelA = "Block-B";        String hostelB = hostelA;             // two references, one immutable object        hostelB = hostelB + "-204";        System.out.println("Immutable: " + hostelA);        System.out.println("Same pooled literal: " + (hostelA == "Block-B"));    }}
Output
Mutable:   Block-B-204
Immutable: Block-B
Same pooled literal: true

What this code does

  • With the mutable StringBuilder, changing through roomB also changes what roomA sees. If String worked like this, one pooled literal shared across a program could be changed by anyone.
  • With String, hostelB + "-204" makes a new object, so hostelA keeps Block-B and still points to the pooled literal. That is why the pool is safe.

Say the four reasons in this order, one line each, with an example for the first:

  • String pool: many references share one literal safely; if it could change, every user would see the change.
  • Security: a file path, URL or class name checked once cannot be altered after the check.
  • Hashing: the hash code never changes and is cached, so strings are fast and safe HashMap keys.
  • Thread safety: nobody can write to a string, so threads share it without locks.

Literal vs new String(), and intern()

The string pool is a shared area on the heap where Java keeps one copy of each string literal. Two literals with the same text point to the same pooled object, which is safe because strings are immutable.

A literal goes into the pool once; new String(...) always makes a separate object. This program compares both with ==, equals and intern().

The string pool. Variables a and b are both literals "upi", so both point to the one "upi" object inside the string pool. Variable c is new String("upi") and points to a separate "upi" object outside the pool. So a == b is true, a == c is false and a.equals(c) is true.

Example 3 · Literals, new String() and intern()

PoolDemo.javaJava
public class PoolDemo {    public static void main(String[] args) {        String a = "upi";        String b = "upi";        String c = new String("upi");        String d = c.intern();
        System.out.println("a == b: " + (a == b));        System.out.println("a == c: " + (a == c));        System.out.println("a.equals(c): " + a.equals(c));        System.out.println("a == d: " + (a == d));        System.out.println("c == d: " + (c == d));    }}
Output
a == b: true
a == c: false
a.equals(c): true
a == d: true
c == d: false

What this code does

  • a and b are the same pooled object. c is a separate heap object created by new, so a == c is false even though equals is true.
  • c.intern() returns the pooled "upi", which is exactly a. c itself is still the separate heap object, so c == d is false.

So new String("abc") creates up to two objects: the pooled literal (only if it was not there already) and the new heap object. intern() goes the other way: it returns the pooled copy for that text, adding it to the pool if needed.

Revise: equals vs == (opens in a new tab)

Predict the output: == vs equals

A compile-time constant is a value the Java compiler can work out before the program runs, such as two literals joined with + or a final variable set to a literal. The result is pooled like any literal.

Joining literals happens in the compiler, joining with a normal variable happens at run time. This program prints five comparisons, so predict each one before you run it.

Example 4 · Compile-time constants vs run-time joins

ConstantPuzzle.javaJava
public class ConstantPuzzle {    public static void main(String[] args) {        String full = "java";        String joinedLiterals = "ja" + "va";        // done by the compiler        String part = "ja";        String joinedAtRuntime = part + "va";       // done while running        final String finalPart = "ja";        String joinedFinal = finalPart + "va";      // final + literal: compile time
        System.out.println(full == joinedLiterals);        System.out.println(full == joinedAtRuntime);        System.out.println(full == joinedFinal);        System.out.println(full == joinedAtRuntime.intern());        System.out.println(full.equals(joinedAtRuntime));    }}
Output
true
false
true
true
true

What this code does

  • "ja" + "va" and finalPart + "va" are compile-time constants, so the compiler stores the pooled "java" and == is true.
  • part + "va" runs at run time and creates a new object, so == is false until you intern() it. equals is true in every case.

Compile-time joins are pooled, so "ja" + "va" == "java" is true, and so is a final variable joined to a literal. A join with an ordinary variable creates a new object at run time, so == gives false while equals is always true for the same text.

Predict the output

Predict the string puzzle

Read each snippet and pick what it prints.

Round 1 of 3

String a = "java";
String b = "ja" + "va";
System.out.println(a == b);

Traps: concat without assignment, == in conditions

Two small habits cost marks in tests and code reviews: ignoring the result of a String method, and using == to compare text. This program shows both bugs and their fixes.

Example 5 · Trap: == in a login check

RoleCheck.javaJava
public class RoleCheck {    static String roleFromInput(String line) {        return line.substring(line.indexOf(':') + 1);   // built at run time, like real input    }
    public static void main(String[] args) {        String role = roleFromInput("user:admin");        System.out.println("role = " + role);
        System.out.println("== check:      " + (role == "admin"));        System.out.println("equals check:  " + "admin".equals(role));
        String missing = null;        System.out.println("null-safe:     " + "admin".equals(missing));        try {            System.out.println(missing.equals("admin"));        } catch (NullPointerException e) {            System.out.println("missing.equals(...) threw NullPointerException");        }    }}
Output
role = admin
== check:      false
equals check:  true
null-safe:     false
missing.equals(...) threw NullPointerException

What this code does

  • substring creates a new string at run time, so role == "admin" is false even though it prints admin. A quick test with a hard-coded literal would have hidden this bug.
  • Putting the literal first, "admin".equals(role), compares text and returns false for null instead of throwing.

Calling s.concat("!"); or name.trim(); and ignoring the result changes nothing; assign it, as in s = s.concat("!");. Comparing with == may pass with literals and then fail for text from input, a database or substring. Write "admin".equals(role): it compares text and is safe when role is null.

Find the bug

Find the string bug

Each snippet has one wrong line. Tap it, then check the fix.

Trim the name, then print it.

Round 1 of 3

Next step

Check your understanding

12 quick questions