Sobes.tech
Junior

What are the purposes of the equals() and toString() methods in Java?

sobes.tech AI

Answer from AI

The equals() method is used to compare objects for logical equivalence, meaning it determines whether two objects represent the same value or entity, regardless of whether they are the exact same object in memory.

The toString() method is used to obtain a string representation of an object. By default, it returns a string containing the class name and its hash code, but it is often overridden to provide a more informative description of the object's state.

public class ExampleObject {
    private int id;
    private String name;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // Reference comparison
        if (o == null || getClass() != o.getClass()) return false; // Type and null check
        ExampleObject that = (ExampleObject) o; // Type casting
        return id == that.id && // Comparison of significant fields
               name.equals(that.name);
    }

    @Override
    public int hashCode() {
        // Overriding hashCode is necessary when overriding equals
        return Objects.hash(id, name);
    }

    @Override
    public String toString() {
        return "ExampleObject{" +
               "id=" + id +
               ", name='" + name + '\'' +
               '}';
    }

    public static void main(String[] args) {
        ExampleObject obj1 = new ExampleObject(1, "Test");
        ExampleObject obj2 = new ExampleObject(1, "Test");
        ExampleObject obj3 = new ExampleObject(2, "Another");

        // Using equals()
        System.out.println("obj1 equals obj2: " + obj1.equals(obj2)); // true - logically equivalent
        System.out.println("obj1 equals obj3: " + obj1.equals(obj3)); // false - different objects

        // Using toString()
        System.out.println("obj1 toString(): " + obj1.toString()); // Will output the string representation of the object
    }
}