Reference Equality with ==: Comparing Memory Addresses
You'll learn: How the == operator works with reference types—by comparing memory addresses, not object contents.
When you use == with reference types (objects, arrays, Strings not interned), Java compares the memory addresses stored in the reference variables, not the actual data inside the objects.
Think of it like comparing two pieces of paper that each have an address written on them. If both papers show "123 Main Street," == returns true. If one says "123 Main Street" and the other says "456 Elm Avenue," == returns false—even if the houses at those addresses look identical inside.
How It Works
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = s1;
System.out.println(s1 == s2); // false - different objects, different addresses
System.out.println(s1 == s3); // true - same object, same address
Even though s1 and s2 contain the same text ("hello"), they point to different objects in the heap—different memory addresses. So s1 == s2 is false.
But s3 was assigned the reference from s1, so both variables point to the exact same object. The addresses match, so s1 == s3 is true.
Why This Matters
When comparing objects, == tells you if two references point to the same instance, not whether the objects are logically equivalent. For content comparison, you'll need other mechanisms (which you'll learn later).
Key Takeaway:
The == operator compares reference variables by memory address—it checks if two references point to the same object, not whether the objects have identical content.