Sitemap

Writing is for everyone.Register for Medium Day

When "abc" == new String("abc") Returns true (Yes, Really)

2 min readJun 3, 2025

🧠 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 String objects
  • Only works automatically for compile-time constants
String a = "hello";      // goes into pool
String b = "he" + "llo"; // compiler optimizes, still pooled
String c = new

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web
Already have an account? Sign in
Umadevi R

Written by Umadevi R

Software Developer at PayPal | EX-Amazon | Sharing insights on coding, interview preparation, software architecture, and emerging tech trends. 🚀 #FAANG

No responses yet

Write a response

Recommended from Medium

See more recommendations