Testing String Identity vs Equality
You'll learn how to distinguish between checking if two strings are the same object versus checking if they have the same content.
The Core Distinction
In Java, there are two fundamentally different ways to compare strings:
==(identity check): Tests whether two references point to the exact same object in memoryequals()(equality check): Tests whether two string objects contain the same sequence of characters
Because strings are immutable and Java uses string pooling for literals, this distinction matters more than you might expect.
Think of It Like House Addresses
Imagine two houses with identical floor plans. equals() checks if the layouts match (content comparison). The == operator checks if you're literally talking about the same house at the same address (identity comparison).
When They Differ
String a = "hello";
String b = "hello"; // same literal, same pool object
String c = new String("hello"); // explicitly created new object
System.out.println(a == b); // true (same pooled object)
System.out.println(a == c); // false (different objects)
System.out.println(a.equals(c)); // true (same content)
String literals share the same pooled instance, so a and b refer to the identical object. But c was explicitly constructed, creating a separate object with identical content.
Why This Matters
Using == for string comparison is almost always a bug. You typically care about what the string says, not which object it is. Always use equals() for content comparison unless you specifically need identity semantics.
Key Takeaway:
Use == to test if two string variables refer to the same object in memory; use equals() to test if they contain the same characters. For logical comparison, always prefer equals().