C

Core Java tutorial for beginners

Clean • Professional

Java - Object Class Methods (toString(), equals(), and hashCode() Explained)

6 minute

Object Class Methods in Java

In Java, every class implicitly inherits from the Object class, which is the root class of the Java class hierarchy.

That means all Java classes — whether built-in or user-defined — automatically have Object class methods available.

The three most commonly used methods are:

learn code with durgesh images

  1. toString() – returns a string representation of an object.
  2. equals() – compares two objects for equality.
  3. hashCode() – returns an integer value (hash code) for efficient object comparison in hash-based collections.

These methods are fundamental for object comparison, debugging, and collection frameworks.


1. toString() Method

  • The toString() method returns a textual (string) representation of an object.
  • It’s automatically called when you print an object using System.out.println().

Default Behavior

By default, it returns:

ClassName@HexadecimalHashCode

Example – Default toString()

class Student {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class ToStringExample {
    public static void main(String[] args) {
        Student s = new Student(101, "Aman");
        System.out.println(s); // Implicitly calls toString()
    }
}

Output (Default):

Student@5ca881b5

Overriding toString()

You can override toString() to display meaningful information about your object.

class Student {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student[id=" + id + ", name=" + name + "]";
    }
}

public class ToStringOverride {
    public static void main(String[] args) {
        Student s = new Student(101, "Aman");
        System.out.println(s);
    }
}

Output (Overridden):

Student[id=101, name=Aman]

2. equals() Method

The equals() method checks whether two objects are equal in terms of content.

Default Behavior

The default equals() method in Object compares references, not actual content:

Object.equals(Object obj) → returns true if both references point to the same memory location.

Example – Default equals()

class Demo {
    int value;

    Demo(int value) {
        this.value = value;
    }
}

public class EqualsExample {
    public static void main(String[] args) {
        Demo d1 = new Demo(10);
        Demo d2 = new Demo(10);

        System.out.println(d1.equals(d2)); // false (different objects)
    }
}

Output:

false

Overriding equals()

To compare object content, override the equals() method.

class Demo {
    int value;

    Demo(int value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        Demo d = (Demo) obj;
        return value == d.value;
    }
}

public class EqualsOverride {
    public static void main(String[] args) {
        Demo d1 = new Demo(10);
        Demo d2 = new Demo(10);

        System.out.println(d1.equals(d2)); // true
    }
}

Output:

true

3. hashCode() Method

The hashCode() method returns an integer value (hash code) used by hash-based collections like:

  • HashMap
  • HashSet
  • Hashtable

Default Behavior

The default implementation returns a unique integer (usually derived from memory address).

Overriding hashCode()

Whenever you override equals(), you should also override hashCode() to maintain consistency — otherwise, hash-based collections may behave unpredictably.

class Demo {
    int value;

    Demo(int value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        Demo d = (Demo) obj;
        return value == d.value;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }
}

public class HashCodeExample {
    public static void main(String[] args) {
        Demo d1 = new Demo(10);
        Demo d2 = new Demo(10);

        System.out.println("Equals: " + d1.equals(d2));
        System.out.println("HashCodes: " + d1.hashCode() + " & " + d2.hashCode());
    }
}

Output:

Equals: true
HashCodes: 10 & 10

Rule:

If two objects are equal (equals() returns true), they must have the same hash code.

However, different objects can have the same hash code (hash collision).


Key Differences Between Methods

MethodPurposeDefault BehaviorCommon Override Use
toString()Converts object to StringPrints class name + hash codeTo display readable info
equals()Compares two objectsCompares memory referencesCompare actual data
hashCode()Returns integer hash codeBased on memory addressFor HashSet, HashMap, etc.

Real-Life Example

import java.util.HashSet;

class Employee {
    int id;
    String name;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Employee)) return false;
        Employee e = (Employee) o;
        return id == e.id && name.equals(e.name);
    }

    @Override
    public int hashCode() {
        return id + name.hashCode();
    }

    @Override
    public String toString() {
        return "Employee[id=" + id + ", name=" + name + "]";
    }
}

public class ObjectMethodsDemo {
    public static void main(String[] args) {
        HashSet<Employee> set = new HashSet<>();
        set.add(new Employee(1, "Aman"));
        set.add(new Employee(1, "Aman")); // Duplicate

        System.out.println(set); // Only one object stored
    }
}

Output:

[Employee[id=1, name=Aman]]

Because equals() and hashCode() are properly overridden, duplicates are avoided.


Points to Remember

  • All classes in Java implicitly extend Object.
  • Override toString(), equals(), and hashCode() for custom behavior.
  • Always override hashCode() when you override equals().
  • Use Objects.equals() and Objects.hash() (Java 7+) for null-safe comparisons.
  • These methods are crucial for collection operations, object comparison, and debugging.
Article 0 of 0