Java String Comparison Gotcha: '==' vs equals()

While solving DSA problems recently, I encountered a small yet significant detail in Java that can lead to incorrect answers and silent bugs. I was comparing two strings like this: String s1 = new String("abbc"); String s2 = new String("abbc"); At first glance, it seems obvious that both strings are identical. However, when I checked: s1 == s2 // false This result surprised me. The reason is that in Java, the "==" operator does not compare the actual string values; it compares memory references. Even though both strings contain "abbc," they are two different objects created in memory. What actually works is: s1.equals(s2) // true The .equals() method compares the content inside the objects, which is typically what we want when working with Strings. This can become even more confusing with string literals: String a = "DSA"; String b = "DSA"; a == b // true In this case, Java uses the String Constant Pool, so both variables point to the same object. This can make == appear to work, but relying on it is risky and inconsistent. Key takeaways from this: - "==" checks reference equality, not value - .equals() checks actual string content - String Pool optimizations can hide bugs - One wrong operator can disrupt DSA logic, HashMaps, or real-world code DSA isn’t just about algorithms; it compels you to understand how the language behaves under the hood, truly. Have you ever lost time debugging something that came down to a single operator? #Java #DSA #Programming #SoftwareEngineering #JVM #CleanCode #CodingInterviews #BackendDevelopment #ProblemSolving 

To view or add a comment, sign in

Explore content categories