== vs equals() with Interned Strings
What you'll learn: How string interning affects the choice between == and equals() for string comparison.
Now that you understand the intern pool and when strings are interned, it's time to see how this impacts comparison logic.
The Core Distinction
When strings are interned (either as literals or explicitly via intern()), they share the same reference in the pool. This means == — which checks reference equality — will return true when comparing interned strings with identical content.
However, when strings are not interned (created at runtime via new String(), concatenation, or stream operations), they occupy different memory locations even if their content is identical. In these cases, == returns false, and you must use equals() to compare their values.
The Analogy
Think of interned strings as people meeting at a designated landmark (the pool). If two people say "meet at the Eiffel Tower," they'll be at the same physical location (== works). But if one person is at a replica Eiffel Tower in Las Vegas, they're at different locations even though both towers look identical — you'd need to compare their appearance (equals()) rather than their GPS coordinates (==).
The Practical Rule
String s1 = "hello"; // interned
String s2 = "hello"; // same interned reference
String s3 = new String("hello"); // NOT interned
String s4 = s3.intern(); // now interned
System.out.println(s1 == s2); // true (both point to pool)
System.out.println(s1 == s3); // false (s3 is heap object)
System.out.println(s1 == s4); // true (s4 points to pool)
System.out.println(s1.equals(s3)); // true (content match)
Always use equals() for string comparison unless you specifically know both strings are interned and are using == for performance-critical reference checks.
Key Takeaway: Interned strings enable == reference equality checks, but equals() is the safe, universal choice for comparing string content regardless of interning status.