Unit 3 Cycle 1 Day 16: toString and equals

Unit 3 Foundation (Cycle 1) Day 16 of 28 Foundation

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.

public class Coin { private String name; private double value; public Coin(String n, double v) { name = n; value = v; } public boolean equals(Object obj) { Coin other = (Coin) obj; return this.value == other.value; } public String toString() { return name + " ($" + value + ")"; } }

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.

Review this topic: Section 3.16 — Object Superclass • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.