SyntaxPilot
Courses/Java/Lesson 22

Java · Lesson 22 of 51 · 11 min

final and the Object class: equals, hashCode, toString

queued

These are the notes for Java episode 22. Episode 21 ended with a mystery: printing a duck shows something like Duck@1b6d3586, and two ducks with the same name aren't equal, even though we never wrote toString or equals. Today you solve it. First, the keyword final: a shop's GST rate that one method silently set to zero, fixed with a final variable, then final methods (a cheat account can't skip the balance check) and final classes (why String is final), and the difference between a final reference and the object it points to. Then the secret parent of every class, Object: why printing an object shows Book@2a139a55, why == and the default equals both say "different", how to override toString and equals, and why a HashSet still keeps a duplicate until you also override hashCode. Every example was run with javac 21.

Part 1: final

The problem: one line changed the tax for every bill

An online shop adds 18% GST to every bill, stored in one shared variable. For a festival banner, a new developer writes a method that sets GST = 0 "just for the banner":

public class Main {
    static double GST = 0.18;

    static double bill(double price) {
        return price + price * GST;
    }

    static void festivalOffer() {
        GST = 0;   // "just for the offer banner"
    }

    public static void main(String[] args) {
        System.out.println(bill(1000));
        festivalOffer();
        System.out.println(bill(1000));
    }
}
1180.0
1000.0

Same item, different bill: every bill after the banner went out with no tax. Nothing stopped it, because a normal variable can be reassigned from anywhere it is visible.

Real-life example: written in pen, not pencil

In real life In Java
Date of birth printed on your ID card final variable: assigned once, never reassigned
Exam rules no teacher may rewrite final method: inherited, but can't be overridden
A sealed medicine pack nobody may repack final class: can't be extended

final variables

Add one word, static final double GST = 0.18;, and the same program no longer compiles:

Main.java:9: error: cannot assign a value to static final variable GST
        GST = 0;   // "just for the offer banner"
        ^
1 error
  • A final variable gets a value exactly once.
  • A static final field is a constant; by convention it's written in UPPER_SNAKE_CASE (GST, MAX_SPEED).
  • A final field can be assigned where it's declared or in every constructor (a "blank final"):
class Order {
    final int id;
    final String item;
    Order(int id, String item) {
        this.id = id;
        this.item = item;
    }
}
public class Main {
    public static void main(String[] args) {
        Order o = new Order(101, "Masala chai");
        System.out.println(o.id + " " + o.item);
    }
}
101 Masala chai

Forget to assign it in a constructor:

Main.java:3: error: variable id might not have been initialized
    Order() { }
              ^
  • Parameters and local variables can be final too: static int twice(final int n) { n = n * 2; ... } gives error: final parameter n may not be assigned.

final methods and final classes

class Account {
    double balance = 1000;
    final boolean withdraw(double amount) {
        if (amount > balance) return false;
        balance -= amount;
        return true;
    }
}

class Cheat extends Account {
    @Override
    boolean withdraw(double amount) {
        balance -= amount;
        return true;
    }
}

final class Upi { }
class FakeUpi extends Upi { }

public class Main {
    public static void main(String[] args) {
        Account a = new Cheat();
        System.out.println(a.withdraw(5000));
    }
}
Main.java:19: error: cannot inherit from final Upi
class FakeUpi extends Upi { }
                      ^
Main.java:12: error: withdraw(double) in Cheat cannot override withdraw(double) in Account
    boolean withdraw(double amount) {
            ^
  overridden method is final
2 errors
  • A final method keeps a safety rule exactly as the parent wrote it; without final, the cheat would withdraw 5000 from a balance of 1000.
  • A final class can't be extended at all. String, Integer and the other wrapper classes are final: class MyString extends String { } gives error: cannot inherit from final String. That protects String's immutability (episode 9): nobody can slip in a "String" subclass that changes.

final locks the reference, not the object

final int[] marks = { 80, 90 };
marks[0] = 35;          // OK: the array's contents change
marks = new int[3];     // error: cannot assign a value to final variable marks

final fixes the arrow (which object the variable points to), not the object's contents. A final StringBuilder can still be appended to; a final array's elements can still change.

Part 2: the Object class

The problem: is this book already on the shelf?

A school library's catalogue program stores every book as an object. Someone donates Java Basics (ISBN 978-81); we already have one. We want to print the record and check whether the two are the same book:

class Book {
    String isbn;
    String title;
    Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
}

public class Main {
    public static void main(String[] args) {
        Book a = new Book("978-81", "Java Basics");
        Book b = new Book("978-81", "Java Basics");
        System.out.println(a);
        System.out.println(a == b);
        System.out.println(a.equals(b));
    }
}
Book@2a139a55
false
false

(The hex number changes from run to run.) == is false because a and b are two different objects: == compares the references (arrows), as in episode 14. But equals is false too, and we never wrote equals or anything that prints Book@....

Every class secretly extends Object

class Book { } means class Book extends Object { }. Every class in Java has java.lang.Object at the top of its family tree, and inherits its methods:

Method Default behaviour Usually override?
toString() class name + @ + hash code in hex (Book@2a139a55) yes, for readable output
equals(Object o) same as ==: is it the very same object? yes, for "same meaning"
hashCode() a number per object (by default tied to the object's identity) yes, whenever you override equals
getClass() the object's runtime class no (it's final)
class Book { }
public class Main {
    public static void main(String[] args) {
        Object o = new Book();
        System.out.println(o.getClass().getSimpleName());
        System.out.println(o instanceof Object);
        String s = "chai";
        Object t = s;
        System.out.println(t.toString() + " " + t.equals("chai"));
    }
}
Book
true
chai true

The defaults know nothing about your fields, so we override them (polymorphism, episode 19). println(x) calls x.toString() for you, and so does "text" + x.

Overriding toString and equals

import java.util.HashSet;

class Book {
    String isbn;
    String title;
    Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
    @Override
    public String toString() {
        return title + " (" + isbn + ")";
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book other)) return false;
        return isbn.equals(other.isbn);
    }
}

public class Main {
    public static void main(String[] args) {
        Book a = new Book("978-81", "Java Basics");
        Book b = new Book("978-81", "Java Basics");
        System.out.println(a);
        System.out.println(a.equals(b));
        HashSet<Book> shelf = new HashSet<>();
        shelf.add(a);
        shelf.add(b);
        System.out.println("Books on shelf: " + shelf.size());
    }
}
Java Basics (978-81)
true
Books on shelf: 2

The equals recipe: same object → true; not the right type (or null, since null instanceof Book is false) → false; otherwise compare the fields that define "the same". But the HashSet (a collection that keeps only unique items) still holds two books.

Real-life example: find the shelf first, then compare

A big library In Java
Thousands of books; comparing with every one is slow HashSet / HashMap need fast lookup
Each book gets a shelf number computed from the book hashCode() picks a bucket
Compare only the books on that shelf equals() is called only within the bucket
Same book filed on different shelves is never compared equal objects with different hash codes break the set

We didn't override hashCode, so each object got an identity-based number: the two copies landed in different buckets and equals was never called.

Overriding hashCode

import java.util.HashSet;
import java.util.Objects;

class Book {
    String isbn;
    String title;
    Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
    @Override
    public String toString() {
        return title + " (" + isbn + ")";
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book other)) return false;
        return isbn.equals(other.isbn);
    }
    @Override
    public int hashCode() {
        return Objects.hash(isbn);
    }
}

public class Main {
    public static void main(String[] args) {
        Book a = new Book("978-81", "Java Basics");
        Book b = new Book("978-81", "Java Basics");
        System.out.println(a);
        System.out.println(a.equals(b));
        HashSet<Book> shelf = new HashSet<>();
        shelf.add(a);
        shelf.add(b);
        System.out.println("Books on shelf: " + shelf.size());
    }
}
Java Basics (978-81)
true
Books on shelf: 1

The equals/hashCode contract

  1. If a.equals(b) is true, then a.hashCode() == b.hashCode() must be true.
  2. Equal hash codes do not mean equal objects (different books can share a shelf: a collision).
  3. equals must be reflexive (a.equals(a)), symmetric, transitive, consistent, and a.equals(null) is false.
  4. Build both from the same fields. Objects.hash(field1, field2, ...) and Objects.equals(x, y) (null-safe) help.

String, Integer and the other library classes already follow this, which is why they work as HashSet items and HashMap keys.

The classic trap: equals(Book) is an overload

@Override
public boolean equals(Book other) {
    return isbn.equals(other.isbn);
}
Main.java:3: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

Object's equals takes an Object; a Book parameter makes a new overloaded method that HashSet never calls. Always write @Override and it catches this. Similarly, toString() must be public: error: toString() in Book cannot override toString() in Object / attempting to assign weaker access privileges; was public.

What you just invented

Problem Fix
A shared value anyone can change final variable / static final constant
A child overrides a safety rule final method
Someone subclasses a class that must not change final class
Printing shows Book@2a139a55 override toString()
Two books with the same ISBN aren't "equal" override equals(Object)
HashSet keeps the duplicate override hashCode() with the same fields

The next problem: each book has chapters. A Chapter class makes no sense outside a Book, yet it sits in the open as a top-level class anyone can use. And sometimes you need a tiny class exactly once; writing a whole named class for it feels heavy. Episode 23: inner, nested and anonymous classes.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
Reassigning a static final error: cannot assign a value to static final variable GST final: assigned once use a separate local variable
Reassigning a final local/array variable error: cannot assign a value to final variable marks the reference is fixed change contents, not the variable
Final field not set in a constructor error: variable id might not have been initialized every constructor must assign it once assign it in each constructor
Assigning a final parameter error: final parameter n may not be assigned parameters can be final too use a new local
Overriding a final method error: withdraw(double) in Cheat cannot override withdraw(double) in Account / overridden method is final the parent locked the rule don't override it
Extending a final class error: cannot inherit from final Upi sealed class use it (composition), don't extend it
equals(Book other) with @Override error: method does not override or implement a method from a supertype must take Object equals(Object o)
toString() without public error: toString() in Book cannot override toString() in Object / attempting to assign weaker access privileges; was public Object's is public public String toString()
Overriding equals but not hashCode no error; HashSet keeps duplicates, HashMap lookups fail equal objects in different buckets override both, same fields
a.equals(b) when a is null java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<local1>" is null can't call a method on null Objects.equals(a, b)

Mini project: a library catalogue without duplicates

import java.util.HashSet;
import java.util.Objects;

class Student {
    int roll;
    String name;
    Student(int roll, String name) { this.roll = roll; this.name = name; }
    @Override public String toString() { return roll + ":" + name; }
    @Override public boolean equals(Object o) {
        return o instanceof Student s && roll == s.roll;
    }
    @Override public int hashCode() { return Objects.hash(roll); }
}

public class Main {
    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<>();
        set.add(new Student(1, "Aarav"));
        set.add(new Student(2, "Meena"));
        set.add(new Student(1, "Aarav K."));
        System.out.println(set.size() + " " + set.contains(new Student(2, "?")));
    }
}
2 true

Delete the hashCode() method and run again:

3 false

Without hashCode, the duplicate roll number gets in, and contains can't find Meena.

Practice

  1. Make MAX_BOOKS_PER_STUDENT = 3 a constant in a Library class. Try changing it in main. What's the message?
  2. Predict: String a = "Java"; String b = new String("Java"); System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()));
  3. Why is it a bad idea to include a field that changes (like copiesAvailable) in hashCode() for objects stored in a HashSet?
Solutions

1. static final int MAX_BOOKS_PER_STUDENT = 3; then Library.MAX_BOOKS_PER_STUDENT = 5; gives error: cannot assign a value to static final variable MAX_BOOKS_PER_STUDENT.

2.

true true

String overrides equals (same characters) and hashCode (computed from the characters), following the contract.

3. If the field changes after the object is added, its hash code changes, so the set looks in a different bucket and can no longer find (or remove) it. Use fields that don't change, ideally final ones.

Quick quiz

class Pen {
    String color;
    Pen(String c) { color = c; }
    @Override
    public boolean equals(Object o) {
        return o instanceof Pen p && color.equals(p.color);
    }
}
// in main:
Pen x = new Pen("blue");
Pen y = new Pen("blue");
System.out.println((x == y) + " " + x.equals(y));

A) true true B) false false C) false true D) true false

Answer

C. == compares references: two different objects, false. The overridden equals compares colors: both blue, true. (This Pen breaks the contract by not overriding hashCode: fine for this quiz, wrong in a HashSet.)

Interview questions

  1. What does final mean for a variable, a method and a class? Variable: assigned once. Method: can't be overridden. Class: can't be extended.
  2. Why is String final? To guarantee immutability and safety (strings are used for class names, file paths, keys in maps, the string pool); no subclass can change their behaviour.
  3. Can a final reference's object change? Yes; final fixes the reference, not the object's state.
  4. What is the Object class? java.lang.Object, the root of every class hierarchy; it provides toString, equals, hashCode, getClass and others.
  5. == vs equals? == compares references (same object) for objects, values for primitives; equals compares meaning, as defined by the class.
  6. What is the equals/hashCode contract? Equal objects must have equal hash codes; override both together using the same fields.
  7. What happens if you override equals but not hashCode? Hash-based collections misbehave: duplicates in HashSet, failed lookups in HashMap.
  8. What does the default toString print? getClass().getName() + "@" + Integer.toHexString(hashCode()).
  9. What is a blank final? A final field without an initialiser, which every constructor must assign exactly once.

Glossary

Term Meaning Example
final variable Can be assigned only once final int id;
Constant A static final field, named in UPPER_CASE static final double GST = 0.18;
Blank final A final field assigned in the constructor this.id = id;
final method Can't be overridden by subclasses final boolean withdraw(...)
final class Can't be extended final class Upi, String
Object The parent of every Java class class Book extends Object (implicit)
toString() Returns the text form of an object Java Basics (978-81)
equals(Object) Decides whether two objects mean the same thing same ISBN
hashCode() An int used to pick a bucket in hash-based collections Objects.hash(isbn)
Hash code A number computed from an object Book@2a139a55 shows it in hex
Bucket A slot in a hash table chosen by the hash code the library shelf
Collision Different objects with the same hash code two books on one shelf
HashSet A collection that stores unique items using hashCode + equals shelf.add(a)
Reference equality ==: the very same object a == b
Logical equality equals: same meaning a.equals(b)
@Override Asks the compiler to check that a method really overrides catches equals(Book)

Summary

  • final variable: assigned once (static final = constant). final method: can't be overridden. final class: can't be extended (String is final).
  • final locks the reference, not the object's contents.
  • Every class extends Object, inheriting toString, equals, hashCode, getClass.
  • Override toString() for readable output; println calls it for you.
  • == asks "same object?"; equals asks "same meaning?". Override equals(Object), never equals(Book).
  • Override equals and hashCode together, from the same fields, or hash-based collections break.
  • Next: a Chapter that only belongs inside a Book, and a class needed only once. Episode 23: inner, nested and anonymous classes.