Unit 3 Cycle 1 Day 16: toString and equals
Share
toString and equals
Section 3.16 — Object Superclass
Key Concept
Every class in Java implicitly extends Object, which provides toString() and equals() methods. The default toString() returns the class name and hash code, which is not useful. Overriding toString() to return a meaningful string representation is a common AP exam task. The default equals() uses == (reference comparison). Overriding equals() to compare field values requires casting the parameter from Object to the specific class type. Both methods are frequently tested on the AP exam.
Consider the following class.
What does the following code print?Coin a = new Coin("Quarter", 0.25); Coin b = new Coin("Quarter", 0.25); System.out.println(a.equals(b) + " " + (a == b));
Answer: (B) true false
a.equals(b): compares values, 0.25 == 0.25 is true. a == b: compares references, two different objects created with new are never ==. Result: true false.
Why Not the Others?
(A) a == b is false because they are different objects in memory.
(C) a.equals(b) uses the overridden method which compares value fields.
(D) equals returns true (same value), == returns false (different objects).
Common Mistake
equals() compares content (when overridden). == compares references (memory addresses). Two objects created with new are always different references.
AP Exam Tip
Always override equals() for content comparison and toString() for meaningful string output. The AP exam tests both.