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.
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));
a == b: true
a == c: false
a == d: true
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