String Immutability, the String Pool and == vs equals
45 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}pune PUNE pune pune 411001
What this code does
- The first two calls return new strings that nobody stores, so
citystill printspune. upperholds the new object whilecityis unchanged.city = city + ...does not modify the old string either: it pointscityat 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
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")); }}Mutable: Block-B-204 Immutable: Block-B Same pooled literal: true
What this code does
- With the mutable
StringBuilder, changing throughroomBalso changes whatroomAsees. IfStringworked like this, one pooled literal shared across a program could be changed by anyone. - With
String,hostelB + "-204"makes a new object, sohostelAkeepsBlock-Band 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
HashMapkeys. - 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().
Example 3 · Literals, new String() and intern()
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)); }}a == b: true a == c: false a.equals(c): true a == d: true c == d: false
What this code does
aandbare the same pooled object.cis a separate heap object created bynew, soa == cisfalseeven thoughequalsistrue.c.intern()returns the pooled"upi", which is exactlya.citself is still the separate heap object, soc == disfalse.
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.
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
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)); }}true false true true true
What this code does
"ja" + "va"andfinalPart + "va"are compile-time constants, so the compiler stores the pooled"java"and==istrue.part + "va"runs at run time and creates a new object, so==isfalseuntil youintern()it.equalsistruein 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
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
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"); } }}role = admin == check: false equals check: true null-safe: false missing.equals(...) threw NullPointerException
What this code does
substringcreates a new string at run time, sorole == "admin"isfalseeven though it printsadmin. A quick test with a hard-coded literal would have hidden this bug.- Putting the literal first,
"admin".equals(role), compares text and returnsfalsefornullinstead 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 3Next step
Check your understanding
12 quick questions