Why Java Devs Should Avoid Using == on Strings

💡 Most Java devs use .equals() for Strings without knowing why == breaks. Here's the full picture — every concept connected. 🔷 String is an Object — and Immutable String is not a primitive. It's an object. And it's immutable — once created, its value never changes. String s = "Java"; s = s + " Dev"; → "Java" is NOT touched → "Java Dev" is a brand new object → 's' just shifts its reference to the new one Immutability is why JVM can safely share and reuse String objects. 🔷 Where Strings Live — The String Pool All objects go into Heap. But String literals go into a special zone inside Heap called the String Pool. The Pool stores only unique values — no duplicates. String s1 = "Java"; → JVM creates "Java" in pool String s2 = "Java"; → already exists → s2 gets same reference s1 == s2 → true ✅ (same object, same address) But new String("Java") bypasses the pool — creates a fresh Heap object. s1 == s3 → false ❌ (different references) s1.equals(s3) → true ✅ (same content) 🔷 What == Actually Does == compares references — the memory address — not values. → Same object → true → Different object, same value → false This is the root cause of every String comparison bug in Java. 🔷 Compile-time vs Runtime — a Trap Most Miss String s2 = "Ja" + "va"; → folded at compile time → pool → s1 == s2 ✅ String part = "Ja"; String s3 = part + "va"; → built at runtime → new Heap object → s1 == s3 ❌ Same output. Completely different memory behavior. 🔷 Default equals() — What Most Don't Know Every class inherits equals() from java.lang.Object. The default implementation? public boolean equals(Object obj) { return (this == obj); } Just == in disguise. Reference comparison — not value. String overrides this — compares characters directly. That's why s1.equals(s3) → true ✅ always. 🔷 intern() — Taking Back Control String s4 = new String("Java").intern(); → intern() fetches the pool reference → s4 now points to the same object as s1 s1 == s4 → true ✅ Useful in performance-sensitive code. In everyday apps — just use .equals(). Immutability → JVM safely shares Strings String Pool → unique literals, no duplicates == → reference comparison, not value Default equals() → also reference comparison String.equals() → overrides it, compares content intern() → pulls Heap object back to pool Not six facts. One connected idea. 💬 Which part clicked for you? What Java concept should I cover next? #Java #JVM #StringPool #BackendDevelopment #SoftwareEngineering #JavaDeveloper #LearnJava

  • diagram, text, letter

To view or add a comment, sign in

Explore content categories