Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

The equals() method compares the current object with another object for content equality rather than reference equality. By default, it compares references (like the == operator), but it can be overridden to compare object fields.

The toString() method returns a string representation of the object. By default, it includes the class name and hash code, but it is often overridden to provide more informative representations, such as the values of the object's fields.

Example of overriding:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @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
        Person person = (Person) o;
        return age == person.age && // Field comparison
               name.equals(person.name); // Using equals for strings
    }

    @Override
    public String toString() {
        return "Person{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
    }
}
What are the purposes of the equals() and toString()… - sobes.tech