Member-only story
When "abc" == new String("abc") Returns true (Yes, Really)
🧠 The JVM’s String Pool is Weird — And You Can Hack It
Ask any Java dev:
System.out.println("abc" == new String("abc")); // true or false?Everyone will say: false, because new String("abc") creates a new object on the heap.
But what if I told you… with a little trick, you can make it return true?
🧪 The Trick: Interning Dynamically Created Strings
public class StringHack {
public static void main(String[] args) {
String s1 = "abc";
String s2 = new String("abc").intern();
System.out.println(s1 == s2); // true 🤯
}
}By calling .intern() on s2, you're telling the JVM:
“Hey, put this string in the intern pool and return the pooled reference.”
Since "abc" is already there as a string literal, intern() returns the exact same reference.
🔍 What’s the Java String Pool?
- It’s a special area in memory for unique, immutable string literals
- Ensures memory efficiency by reusing identical
Stringobjects - Only works automatically for compile-time constants
String a = "hello"; // goes into pool
String b = "he" + "llo"; // compiler optimizes, still pooled
String c = new…