Java == vs equals() in Java

Many developers overlook a small but important difference in Java: == vs .equals() String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true ✔ == compares memory references (whether both variables point to the same object). ✔ .equals() compares the actual content of the objects. Even though s1 and s2 contain the same value, they are stored as different objects in memory, so == returns false. 💡 This distinction becomes critical when working with collections like HashMap, HashSet, or custom objects. Strong Java fundamentals often come down to understanding small details like these. #Java #Programming #JavaDeveloper #Coding #SoftwareEngineering LinkedIn Guide to Networking LinkedIn Learning Community LinkedIn Learning

  • No alternative text description for this image

When we explicitly create Strings using new String("Java"), the JVM allocates separate objects on the heap, even though the literal "Java" itself may already exist in the String Constant Pool. Therefore s1 and s2 reference two different heap objects, making == return false. However, if the Strings were declared like this: String s1 = "Java"; String s2 = "Java"; both variables would reference the same pooled object, and s1 == s2 would actually return true because the JVM reuses the interned String. Another interesting angle is the String.intern() method, which forces a heap String reference to point to the pooled instance: String s1 = new String("Java").intern(); String s2 = "Java"; System.out.println(s1 == s2); // true This subtle distinction becomes especially important in memory optimisation, caching strategies, and high-performance systems where unnecessary heap allocations can affect GC pressure. Sometimes the real Java mastery lies not just in syntax, but in understanding what the JVM is doing under the hood.

To view or add a comment, sign in

Explore content categories