Lesson 21 of 34 · Classes & Objects
Java toString(), equals() and hashCode()
Every Java class quietly inherits a few methods from Object, the root of all classes: toString(), equals() and hashCode(). Chapter 5 explains inheritance in detail — what matters now is that the default versions are rarely what you want, and overriding them correctly is one of the most practical skills in everyday Java.
toString: how an object prints
System.out.println(obj) and string concatenation like "Card: " + card call toString() automatically. The inherited version returns the class name, an @ and a hexadecimal hash code — something like Card@1b6d3586 — which is useless in logs and error messages. Override it:
class Card {
String rank;
String suit;
Card(String rank, String suit) {
this.rank = rank;
this.suit = suit;
}
@Override
public String toString() {
return rank + " of " + suit;
}
}
System.out.println(new Card("Q", "hearts"));
Q of hearts
@Override asks the compiler to check that you really replace an inherited method: misspell it as tostring() and you get a compile error instead of a silent bug. The method must be public, because the original in Object is public.
== vs equals
Card a = new Card("Q", "hearts");
Card b = new Card("Q", "hearts");
System.out.println(a == b);
System.out.println(a.equals(b));
false
false
== asks are these the very same object? equals should ask do these mean the same thing? — but the default equals from Object simply uses ==, so both lines print false until you override it. String overrides equals to compare characters, which is why you always compare Strings with .equals.
Writing equals
@Override
public boolean equals(Object o) {
if (this == o) return true; // the same object
if (!(o instanceof Card other)) return false; // null or another type
return rank.equals(other.rank) && suit.equals(other.suit);
}
The parameter must be Object, not Card. o instanceof Card other checks the type and, if it matches, gives you a Card variable called other (pattern matching, Java 16+). A correct equals keeps a contract: an object equals itself, a.equals(b) gives the same answer as b.equals(a), and x.equals(null) is always false. If a field may be null, compare it with Objects.equals(x, y).
hashCode: the partner of equals
Hash-based collections such as HashSet and HashMap first use hashCode() to pick a bucket and only then call equals inside it. So the rule is strict: equal objects must have equal hash codes. Override both methods or neither.
@Override
public int hashCode() {
return Objects.hash(rank, suit); // needs: import java.util.Objects;
}
Without it, two equal cards land in different buckets, and a HashSet happily stores both "duplicates".
Records do it for you
For classes that mostly carry data, Java 16 added records. One line generates the constructor, accessor methods, equals, hashCode and toString:
record Point(int x, int y) {}
Point p = new Point(1, 2);
System.out.println(p);
System.out.println(p.equals(new Point(1, 2)));
System.out.println(p.x());
Point[x=1, y=2]
true
1
Record fields are final, so records are perfect for small immutable values.
Common mistakes
public boolean equals(Card other)— this overloads instead of overriding, and collections keep calling the originalequals(Object).@Overridecatches the mistake.- Overriding
equalsbut nothashCode—HashSetandHashMapstop finding your objects. - Comparing objects with
==(Strings included) when you mean "equal values". - Printing inside
toString()— it must return the text, not callSystem.out.println.
Assignment
- In class
Card(the fieldsrankandsuitare given):toString()returns"<rank> of <suit>", e.g."Q of hearts"equals(Object o)— two cards are equal when both rank and suit are equalhashCode()— consistent withequals(useObjects.hash)
- In
Main,static int countDistinct(List<Card> cards)returns how many different cards the list contains. AHashSetmakes this a one-liner onceequalsandhashCodework. - Replace the stub class
Coinwith a recordCoin(String metal, int value).
Card queen = new Card("Q", "hearts");
"Drew " + queen; // "Drew Q of hearts"
queen.equals(new Card("Q", "hearts")); // true
new Coin("gold", 5).toString(); // "Coin[metal=gold, value=5]"Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Value objects and equality in other languages
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .