Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 201 ยท Object-Oriented Programming

The Object Class: equals, hashCode and toString

Learn the Object class in Java - overriding equals and hashCode correctly, the contract between them, useful toString, getClass, and the Objects helper methods.

Every class in Java, whether you write extends or not, ultimately inherits from java.lang.Object. That's why you can print any object, put any object in a List<Object>, and call equals on anything. The methods Object provides are the common language that the whole platform relies on: HashMap uses hashCode and equals to find keys, println and string concatenation use toString, and debuggers and logs use both.

The default versions of these methods are rarely what you want for your own data classes. This lesson shows what Object gives you, how to override toString, equals and hashCode correctly (and the real bugs that appear when you don't), what getClass is for, and the java.util.Objects helpers that make all of this shorter and null-safe.

What every object inherits

Method Default behavior Override it?
toString() Class name, @, hash code in hex: Point@1b6d3586 Almost always, for readable output
equals(Object) this == other (same object) For value-like classes
hashCode() A number derived from the object's identity Whenever you override equals
getClass() The runtime Class object Can't (it's final)
clone() Field-by-field copy, protected, needs Cloneable Rarely; see Copying Objects
wait(), notify(), notifyAll() Thread coordination Can't (they're final); see wait and notify
finalize() Deprecated for removal since Java 18 Never; use try-with-resources

toString: make objects readable

toString() is called automatically by string concatenation, IO.println, String.valueOf and collection printing. The default output identifies the object but tells you nothing about its contents:

Java Default toString versus an override

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The hexadecimal part of PlainBook@... changes from run to run, so don't expect to see the same value. A good toString:

  • includes the fields that identify the object and help in debugging;
  • never includes secrets such as passwords or tokens, because toString output ends up in logs;
  • is concise and never throws, even if fields are null.

Treat it as a debugging aid, not a format other code parses. For user-facing text, write a separate method like displayName() or use string formatting.

equals: identity versus equality

== on references asks "are these the same object?" equals is meant to ask "do these objects represent the same value?" Object.equals can't know what your fields mean, so by default it falls back to ==. For String, Integer, LocalDate and records, the JDK already overrides it. For your own classes, you must do it.

Overriding equals correctly means following a contract. For non-null references x, y and z:

  • Reflexive: x.equals(x) is true.
  • Symmetric: x.equals(y) is true exactly when y.equals(x) is true.
  • Transitive: if x.equals(y) and y.equals(z), then x.equals(z).
  • Consistent: repeated calls give the same answer as long as the objects don't change.
  • Null: x.equals(null) is false, and never throws.

Here is the standard shape that satisfies all of them:

Java A correct equals and hashCode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The recipe, step by step:

  1. Take an Object parameter. Writing equals(Isbn other) overloads instead of overriding, so collections, which call equals(Object), never use it. The @Override annotation catches this mistake at compile time.
  2. Check this == o as a cheap shortcut.
  3. Check the type with a pattern: o instanceof Isbn other is false for null, so it handles the null rule for free, and it gives you a typed variable (Pattern Matching).
  4. Compare the significant fields. Use == for primitives (or Double.compare for double, so that NaN equals itself), equals for objects, Objects.equals(a, b) for fields that may be null, and Arrays.equals for arrays.
  5. Override hashCode with the same fields.

The class is final. That's not decoration: equality and inheritance don't mix well, as the next section shows.

instanceof or getClass()?

If a subclass adds a field that matters for equality, you can't keep the contract. Suppose ColorPoint extends Point adds a color and compares it. Then point.equals(colorPoint) may be true (the point only checks x and y) while colorPoint.equals(point) is false: symmetry is broken, and sets containing both behave unpredictably.

Two common ways out:

  • Make value classes final (or use a record, which is final) and use instanceof. This is the usual modern choice.
  • Use getClass() != o.getClass() instead of instanceof, so objects of different classes are never equal. This keeps the contract, but a subclass that adds no fields can't equal its parent either, which surprises users of frameworks that create subclasses (proxies) behind the scenes.

Prefer composition when you want "a point with a color": give ColoredPoint a Point field (Composition).

hashCode: the rule you can't skip

The contract between the two methods is short:

  • If a.equals(b), then a.hashCode() == b.hashCode(). Always.
  • Unequal objects may share a hash code (a collision), but fewer collisions make hash tables faster.
  • The hash code must not change while the object is in a hash-based collection.

HashMap and HashSet first use hashCode to pick a bucket, and only then call equals on the objects in that bucket. If two equal objects have different hash codes, the set looks in the wrong bucket and never even calls your equals:

Java equals without hashCode breaks HashSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The set holds two "equal" coordinates, can't find a third, and the map can't find its own key. Each new Coordinate gets a different identity-based hash code, so lookups go to the wrong bucket. (Very rarely two identity hashes collide and a lookup succeeds by luck, which makes this bug even harder to track down.) Add the missing method and everything works:

Java
@Override
public int hashCode() {
    return Objects.hash(x, y);      // or 31 * Integer.hashCode(x) + Integer.hashCode(y)
}

Objects.hash(...) is convenient, but it creates an array and boxes primitives on every call. For classes used as keys in very hot code, the manual 31 * h + ... form is faster. How HashMap Works Inside explains buckets and why the hash quality matters.

Mutable fields and lost objects

If a field used in hashCode changes while the object is inside a HashSet or used as a HashMap key, the object is now in the "wrong" bucket for its new hash. contains returns false, and remove can't remove it, even though iterating the set still shows it. Base equals/hashCode on fields that never change, or don't mutate objects while they are keys. Immutable classes and records avoid the problem entirely.

getClass: the runtime type

getClass() returns the Class object for the object's actual class at run time, regardless of the variable's declared type. It's useful for logging, debugging and the getClass() style of equals:

Java getClass and the Objects helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

There's exactly one Class object per loaded class, so comparing with == is correct. getClass() on a List<String> returns plain ArrayList, because generic type arguments don't exist at run time (Type Erasure). Class objects are the entry point to Reflection.

The Objects utility class

java.util.Objects (Java 7+) collects small, null-safe helpers for exactly the code you write around equals, hashCode and toString:

Method Use
Objects.equals(a, b) true if both are null or a.equals(b); never throws
Objects.hash(a, b, ...) Combined hash code of several values, for hashCode()
Objects.hashCode(o) o.hashCode(), or 0 for null
Objects.toString(o, fallback) o.toString(), or the fallback for null
Objects.requireNonNull(o, message) Returns o, or throws NullPointerException with your message
Objects.requireNonNullElse(o, other) o if not null, otherwise other (Java 9)
Objects.isNull(o) / nonNull(o) Handy as method references in streams: filter(Objects::nonNull)
Objects.checkIndex(i, length) Throws IndexOutOfBoundsException if i is out of range (Java 9)

requireNonNull in constructors is a professional habit: a null is rejected the moment it enters the object, with a message naming the culprit, instead of causing a confusing NullPointerException much later.

Let records and IDEs do the work

Hand-written equals and hashCode are easy to get subtly wrong, and they must be updated whenever a field is added. In modern Java:

  • For value classes, use a record; the compiler generates correct equals, hashCode and toString from the components.
  • For other classes, let your IDE generate the methods, then review them.
  • For entities with identity (a customer, a bank account), equality usually depends on a stable ID, or the default identity equals is exactly right. Don't override equals just because you can.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class declares public boolean equals(Point other) and no other equals method. What happens with new HashSet<>(List.of(p1, p2)).size() when p1 and p2 have the same fields?

    Collections call equals(Object). A method taking Point is a separate overload that they never use, and hashCode isn't overridden either. @Override would have caught the mistake.
  2. 2. You override equals to compare name and age, but not hashCode. What is the most likely problem?

    Equal objects must have equal hash codes. Without an override, each object has an identity-based hash, so hash collections look in the wrong bucket.
  3. 3. Which statement about the equals/hashCode contract is true?

    Equality implies equal hash codes. The reverse isn't required; different objects may collide, it just makes hash tables slower.
  4. 4. What does Objects.equals(null, null) return, and what does Objects.requireNonNull(null, "id") do?

    Objects.equals treats two nulls as equal and never throws. requireNonNull throws a NullPointerException with your message when the value is null.
  5. 5. Object o = new ArrayList<String>(); What does o.getClass().getSimpleName() return?

    getClass returns the runtime class, not the declared type, and generic type arguments are erased at run time.

Summary

  • Every class inherits from Object: toString, equals, hashCode, getClass, clone, wait/notify and the deprecated finalize.
  • Override toString to show the identifying fields; keep secrets out and don't parse its output.
  • By default equals means ==. Override it with an Object parameter, @Override, a this == o shortcut, an instanceof pattern, and field comparisons; follow the reflexive, symmetric, transitive, consistent and null rules.
  • Always override hashCode with the same fields as equals; otherwise HashSet and HashMap misbehave. Don't change those fields while the object is in a hash collection.
  • Equality and subclassing conflict: make value classes final, or use records.
  • getClass() returns the runtime class; Objects.equals, hash, toString and requireNonNull make these methods short and null-safe.

Next: Copying Objects: Cloning and Copy Constructors, where you'll learn why clone() is tricky and which copying techniques to use instead.