Java Object equals() Method

The Object.equals(Object obj) method in Java is used to determine whether two objects are considered equal.

Table of Contents

  1. Introduction
  2. equals(Object obj) Method Syntax
  3. Examples
    • Basic Equality Check
    • Overriding equals()
    • Handling Null Values
  4. Real-World Use Case
  5. Conclusion

Introduction

The Object.equals(Object obj) method is a member of the Object class in Java. It provides a way to compare two objects for equality. By default, the equals() method compares the memory addresses of the objects, meaning two objects are equal if and only if they refer to the same instance. However, this method can be overridden to provide a custom equality comparison based on the object's state.

equals(Object obj)() Method Syntax

The syntax for the equals(Object obj) method is as follows:

public boolean equals(Object obj)

The method returns true if the specified object is equal to the current object, otherwise, it returns false.

Examples

Basic Equality Check

The default implementation of the equals() method compares the memory addresses of the objects.

Example

public class EqualsExample {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = new String("Hello");

        System.out.println("str1.equals(str2): " + str1.equals(str2));
        System.out.println("str1 == str2: " + (str1 == str2));
    }
}

Output:

str1.equals(str2): true
str1 == str2: false

Overriding equals()

To provide a custom equality comparison, you can override the equals() method in your class.

Example

class Person {
    String name;
    int age;

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }
}

public class CustomEqualsExample {
    public static void main(String[] args) {
        Person person1 = new Person("Ramesh", 30);
        Person person2 = new Person("Ramesh", 30);
        Person person3 = new Person("Suresh", 25);

        System.out.println("person1.equals(person2): " + person1.equals(person2));
        System.out.println("person1.equals(person3): " + person1.equals(person3));
    }
}

Output:

person1.equals(person2): true
person1.equals(person3): false

Handling Null Values

When implementing the equals() method, it's important to handle potential null values to avoid NullPointerException.

Example

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Product product = (Product) obj;
        return Double.compare(product.price, price) == 0 && name.equals(product.name);
    }
}

public class EqualsNullHandlingExample {
    public static void main(String[] args) {
        Product product1 = new Product("Laptop", 800.0);
        Product product2 = null;

        System.out.println("product1.equals(product2): " + product1.equals(product2));
    }
}

Output:

product1.equals(product2): false

Real-World Use Case

Comparing Entities in a Collection

In a real-world scenario, you might need to compare objects in a collection, such as a list of users or products, to determine if they are already present.

Example

import java.util.HashSet;

class User {
    String username;
    String email;

    User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        User user = (User) obj;
        return username.equals(user.username) && email.equals(user.email);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, email);
    }
}

public class CollectionEqualsExample {
    public static void main(String[] args) {
        User user1 = new User("ramesh123", "ramesh@example.com");
        User user2 = new User("suresh456", "suresh@example.com");
        User user3 = new User("ramesh123", "ramesh@example.com");

        HashSet<User> users = new HashSet<>();
        users.add(user1);
        users.add(user2);

        System.out.println("User set contains user3: " + users.contains(user3));
    }
}

Output:

User set contains user3: true

Conclusion

The Object.equals(Object obj) method in Java is a fundamental method for comparing objects. By understanding how to use and override this method, you can effectively implement custom equality logic in your Java applications. Whether you are performing basic equality checks, overriding the method for custom comparisons, handling potential null values, or using it in real-world scenarios, the equals() method provides a reliable way to determine object equality.

Comments