Unit 2 Cycle 1 Day 10: Comparing Objects
Share
Comparing Objects
Section 2.7 — Comparing Objects
Key Concept
Comparing objects in Java requires understanding the difference between reference and value equality. The == operator checks if two references point to the same object in memory. The equals() method (when properly overridden) checks if two objects have equivalent content. For String objects, equals() compares character sequences. For other objects, the default equals() from Object behaves like == unless the class overrides it.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) false true true
s1 == s2: false (different objects created with new). s1 == s3: true (s3 points to the same object as s1). s1.equals(s2): true (same content "hello").
Why Not the Others?
(B) s1 == s2 is false because new String() creates separate objects. == compares references, not content.
(C) s1 == s3 is true because s3 = s1 copies the reference, making them point to the same object.
(D) s1.equals(s2) is true because both strings contain "hello".
Common Mistake
== compares object references (memory addresses). .equals() compares object content. Two objects created with new are always different references, even with identical content.
AP Exam Tip
This is one of the most tested concepts on the AP exam. Always use .equals() for comparing String content. == only returns true if both variables point to the exact same object.