String, immutability and final

Junior Always asked 7 min

On this page

The question

What is the difference between == and equals() when you compare two strings?

30-second answer

== compares references: it is true only when both sides point at the same object. equals() compares the characters. Two literals with the same text share one object from the string pool, so == can happen to be true, but new String("java") or a string built at runtime is a separate object. Always compare text with equals().

Understand it

Which == comparisons are true?

Predict

a and b are the literal "java", c is new String("java"), and d is c.intern().

Which of a == b, a == c and a == d are true?
View as text

a and b are the literal "java", c is new String("java"), and d is c.intern(). The drawing lists the four variables on the left. On the right is the heap, with the string pool drawn inside it, one "java" object in the pool and one outside it. The learner first predicts which of a == b, a == c and a == d are true.

Both literals point at one pooled "java" object, so a == b is true. Arrows join a and b to the pooled object, marked true.

new String("java") always makes a separate object on the heap, so a == c is false. An arrow joins c to the object outside the pool, marked false.

c.intern() returns the pooled object with the same characters, so d and a are one reference: a == d is true. A dashed arrow labelled intern() leads from c's object to the pooled one, and d points at the pooled object, marked true.

equals() compares the characters, so a.equals(c) is true. Compare strings with equals(), never ==. Both objects are highlighted and a.equals(c) is marked true.

a and b are the literal "java", c is new String("java"), and d is c.intern(). The drawing lists the four variables on the left. On the right is the heap, with the string pool drawn inside it, one "java" object in the pool and one outside it. The learner first predicts which of a == b, a == c and a == d are true.

Both literals point at one pooled "java" object, so a == b is true. Arrows join a and b to the pooled object, marked true.

new String("java") always makes a separate object on the heap, so a == c is false. An arrow joins c to the object outside the pool, marked false.

c.intern() returns the pooled object with the same characters, so d and a are one reference: a == d is true. A dashed arrow labelled intern() leads from c's object to the pooled one, and d points at the pooled object, marked true.

equals() compares the characters, so a.equals(c) is true. Compare strings with equals(), never ==. Both objects are highlighted and a.equals(c) is marked true.

Takeaway: == compares references. Literals share one pooled object and intern() returns it, but new String makes another, so compare text with equals().

String += or StringBuilder in a loop?

Compare

Each s += i copies the old text into a new String. 4 iterations create 4 String objects, and 3 of them are garbage.

View as text

The same loop runs 4 times, for i from 0 to 3, building the text "0123" in two ways.

String +=: each s += i copies the old text into a new String. 4 iterations create 4 String objects, and 3 of them are garbage. The drawing shows a row of four strings, "0", "01", "012" and "0123", each copied from the one before. The first three are dashed and marked discarded; only "0123" is kept by s. Badges read 1 new String per +=, 4 String objects and 3 discarded.

StringBuilder: sb.append(i) writes into one buffer 4 times, then toString() creates 1 String. The drawing shows one buffer whose first four cells hold 0, 1, 2 and 3, with 12 free cells left of its capacity of 16. An arrow labelled toString() leads to a single "0123" kept by s. Badges read 1 buffer with 4 appends, 1 String object and 0 discarded.

The same loop runs 4 times, for i from 0 to 3, building the text "0123" in two ways.

String +=: each s += i copies the old text into a new String. 4 iterations create 4 String objects, and 3 of them are garbage. The drawing shows a row of four strings, "0", "01", "012" and "0123", each copied from the one before. The first three are dashed and marked discarded; only "0123" is kept by s. Badges read 1 new String per +=, 4 String objects and 3 discarded.

StringBuilder: sb.append(i) writes into one buffer 4 times, then toString() creates 1 String. The drawing shows one buffer whose first four cells hold 0, 1, 2 and 3, with 12 free cells left of its capacity of 16. An arrow labelled toString() leads to a single "0123" kept by s. Badges read 1 buffer with 4 appends, 1 String object and 0 discarded.

Takeaway: A String never changes, so each += builds a new one and drops the old. StringBuilder appends into one buffer and makes a single String at the end.

Why String is immutableBecause a String never changes, four things are safe. Literals with the same text can share one pooled object. The hash code can be computed once and cached, which makes String a good HashMap key. Threads can share a String without locks. A file path or class name that was checked cannot change after the check.A String neverchangesPool: literals shareone objectHash code cachedonceThreads share itwithout locksSecurity: a checkedvalue stays checked
Why String is immutableBecause a String never changes, four things are safe. Literals with the same text can share one pooled object. The hash code can be computed once and cached, which makes String a good HashMap key. Threads can share a String without locks. A file path or class name that was checked cannot change after the check.A String neverchangesPool: literals shareone objectHash code cachedonceThreads share itwithout locksSecurity: a checkedvalue stays checked
Why String is immutable: four things it makes safe

In code

String a = "java";
String b = "java";
String c = new String("java");
String d = c.intern();
System.out.println(a == b);       // true: one pooled object
System.out.println(a == c);       // false: c is a separate object
System.out.println(a == d);       // true: intern() returns the pooled one
System.out.println(a.equals(c));  // true: same characters
== compares references, equals() compares characters
String s = "";
for (int i = 0; i < 4; i++) {
 Wrong     s += i;                        // a new String every iteration
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
 Right     sb.append(i);                  // one buffer, appended in place
}
String t = sb.toString();          // "0123", a single String
Build a string in a loop with StringBuilder
Where a, b, c and d pointThe variables a, b and d all point at the one java object in the string pool, which lives inside the heap. The variable c points at a separate java object on the heap, outside the pool.aHeap, string pool:the pooled javaobjectbdcHeap, outside thepool: a separate javaobject
Where a, b, c and d pointThe variables a, b and d all point at the one java object in the string pool, which lives inside the heap. The variable c points at a separate java object on the heap, outside the pool.aHeap, string pool:the pooled javaobjectbdcHeap, outside thepool: a separate javaobject
Where a, b, c and d point: the pool and the heap
String s = "java";
 Wrong s.toUpperCase();        // the result is thrown away: s is still "java"
 Right s = s.toUpperCase();    // keep the new object: "JAVA"
String methods return a new String; the original never changes

Solve it

Is this Period class really immutable?

final class Period has private final Date start and private final List<String> tags, set in the constructor and returned by getters. A test changes the Date it passed in, and the period moves. Find every leak and fix them.

  1. Remember what final freezes. A final field cannot point elsewhere, but the object it points to can still change.
  2. Find the ways in. The constructor stores the caller’s Date and List, so the caller keeps a handle on the internals.
  3. Find the ways out. The getters return the same objects, so any reader can mutate them too.
  4. Fix both sides. Use immutable types where they exist (LocalDate), and copy collections in with List.copyOf, which returns an unmodifiable list.
  5. Check. Change the original list after construction, then try to add to the returned list: the period is unchanged and the add throws.
final class LeakyPeriod {
    private final Date start; private final List<String> tags;
 Wrong     LeakyPeriod(Date start, List<String> tags) { this.start = start; this.tags = tags; }   // keeps caller's objects
    Date start() { return start; }
 Wrong     List<String> tags() { return tags; }                                                   // hands them out
}

final class Period {
    private final LocalDate start; private final List<String> tags;
 Right     Period(LocalDate start, List<String> tags) { this.start = start; this.tags = List.copyOf(tags); }
    LocalDate start() { return start; }        // LocalDate is immutable: safe to share
    List<String> tags() { return tags; }       // unmodifiable copy: add() throws
 Right }
Immutable types and copies close every leak

How to answer

  • == asks whether two references point at the same object; equals() asks whether the characters match.
  • Literals with the same text share one pooled object, so == between them is true.
  • new String(...) and strings built at runtime are separate objects, so == is false.
  • intern() returns the pooled object with the same characters.
  • Write "java".equals(s) or Objects.equals(a, b) to stay safe when a value can be null.

Common mistakes

  • Saying == compares the text of two strings; it compares references and only looks right when both are pooled.
  • Relying on == because it worked in a test with literals; strings read from input or built at runtime break it.

Follow-up questions

What is the string pool?

The string pool is a table the JVM (Java Virtual Machine) keeps of shared String objects. Every literal with the same text resolves to one pooled object, and intern() adds or finds a string there. Sharing is safe only because a String never changes. Since Java 7, HotSpot keeps the pool in the main heap rather than in PermGen.

  • Literals with the same text share one pooled object.
  • new String(...) always creates a new object outside the pool.
  • intern() returns the pooled copy, adding the string if it is missing.
  • Sharing is safe because String is immutable.

See it in the infographic: Which == comparisons are true?

Why is String immutable in Java?

Because so much code shares strings. Immutability lets literals share one pooled object, lets a String compute its hash code once and cache it, which makes it a reliable HashMap key, and lets threads share it without locks. It also protects security checks: a file path or class name cannot change after it was validated.

  • Pool sharing: one object can serve every literal with the same text.
  • Cached hash: the hash code never changes, so it is computed once.
  • Thread safety: no thread can see a half-changed String.
  • Security: a checked path, URL or class name stays what was checked.
  • Methods like toUpperCase() return a new String and leave the original alone.
String s = "java";
s.toUpperCase();          // result ignored
System.out.println(s);    // java

See it in the infographic: Which == comparisons are true? See it in the infographic: String += or StringBuilder in a loop?

Why use StringBuilder instead of += to build a string in a loop?

Each += creates a new String and copies every character built so far, because a String cannot change. In a loop that is a new object per iteration and work that grows with the square of the length. StringBuilder appends into one buffer and creates a single String with toString(). Outside loops, a + b + c is fine: javac compiles one expression efficiently.

  • s += x in a loop creates one String per iteration and drops the previous one.
  • StringBuilder appends into one buffer that grows only when it runs out of room.
  • toString() creates the single String at the end.
  • A single + expression is already compiled efficiently.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
    sb.append(i);
}
String s = sb.toString(); // "0123"

See it in the infographic: String += or StringBuilder in a loop?

What is the difference between final, finally and finalize()?

final is a keyword: a final variable is assigned once, a final method cannot be overridden and a final class cannot be extended. finally is the block after try that runs whether or not an exception was thrown, even after a return. finalize() is an Object method the garbage collector may call before reclaiming an object; it is deprecated for removal since Java 18 (JEP 421, a Java Development Kit Enhancement Proposal).

  • final: assign once, no overriding, no subclassing.
  • finally: cleanup that runs after try and catch, even when the try returns.
  • finalize(): unpredictable and deprecated for removal since Java 18; use try-with-resources or a Cleaner.
  • A return inside finally replaces the try block's return value, so avoid it.
static int f() {
    try { return 1; }
    finally { return 2; } // f() returns 2
}

See it in the infographic: String += or StringBuilder in a loop?

With String x = "ja";, why is ("ja" + "va") == "java" true but (x + "va") == "java" false?

"ja" + "va" is a constant expression, so javac joins it at compile time into the literal "java", which is pooled. x is not a constant, so x + "va" runs at runtime and builds a new String object. Declaring final String x = "ja" makes x a constant variable, and the comparison becomes true. The lesson stays the same: compare with equals().

  • Constant expressions are folded by the compiler into one pooled literal.
  • Concatenation with a non-constant variable creates a new String at runtime.
  • A final local initialized with a constant counts as a constant.
String x = "ja";
final String y = "ja";
System.out.println(("ja" + "va") == "java"); // true: folded
System.out.println((x + "va") == "java");    // false: runtime
System.out.println((y + "va") == "java");    // true: constant

See it in the infographic: Which == comparisons are true?

What does intern() do?

It returns the pooled String with the same characters. If the pool has none, it adds this string and returns it. So new String("java").intern() == "java" is true. It is rarely needed in application code; use equals() to compare text.

What is the difference between StringBuilder and StringBuffer?

They offer the same operations, but StringBuffer synchronizes them, so it is safe to share between threads and carries the cost of locking. StringBuilder, added in Java 5, has no locking. Building a string inside one method is single-threaded, so StringBuilder is the default choice.

Does final make an object immutable?

No. final stops the variable from being reassigned, not the object from changing. With final StringBuilder sb, sb.append("x") still compiles and appends. An immutable class needs private final fields, no setters, no subclasses and defensive copies of mutable state, as String has.

Check yourself

1. Given String a = "hi"; String b = new String("hi"); String c = b.intern();, which expressions are true?Choose 2
Show answers
  • a == b: Incorrect. new String creates a separate object, so the references differ.
  • a == c: Correct. intern() returns the pooled object that the literal a already points at.
  • a.equals(b): Correct. equals() compares the characters, and both hold "hi".
  • b == c: Incorrect. b is the separate object; c is the pooled one, so they differ.
2. What happens each time s += i runs inside a loop?
Show answers
  • A new String is created with the old characters copied into it: Correct. A String cannot change, so += builds a new one and the old one becomes garbage.
  • The existing String is changed in place: Incorrect. String is immutable; no method or operator changes an existing String.
  • javac moves one StringBuilder outside the loop for you: Incorrect. javac compiles each += on its own; it does not share one buffer across iterations.
3. What does this code print?
String s = "java";
s.toUpperCase();
System.out.println(s);
Show answers
  • java: Correct. toUpperCase() returns a new String; the result is ignored and s is unchanged.
  • JAVA: Incorrect. That would need s = s.toUpperCase(); String methods never change the original.
  • It does not compile: Incorrect. Ignoring a return value is legal Java.