Core Java: String literals are interned, so == matches constants but not new String

Compile-time string literals share one pooled instance so == is true between them, but new String(...) always creates a distinct object; calling intern() returns the pooled reference, making == true again.

Code
String a = "hello";
String b = "hello";
String c = new String("hello");
String d = c.intern();
System.out.println("a == b: " + (a == b));
System.out.println("a == c: " + (a == c));
System.out.println("a == d: " + (a == d));
Output
a == b: true
a == c: false
a == d: true
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms