All classes in Java are child classes of the Object class that you can find in java.lang package in rt.jar. If you open the Object class, you will see that it has many methods and one of the very important ones that we are going to discuss in this tutorial is the equals(Object obj) method.
Let's open the java.lang.Object class and look at the default implementation of the equals method.
Default implementation of equals method in Object class:public boolean equals(Object obj) {
return (this == obj);
}
As you can see, the default implementation uses double equals-to == comparison of the current object and the object passed on to the equals method. == does the address comparison
Example without overriding equals method:
public class EqualsExampleJava {
public static void main(String[] args) {
Employee employee1 = new Employee(1, "Sam");
Employee employee2 = employee1; //same reference
Employee employeeDup = new Employee(1, "Sam");
System.out.println("employee1 == employee2 => " + (employee1 == employee2));
System.out.println("employee1.equals(employee2) => " + employee1.equals(employee2));
System.out.println("employee1 == employeeDup => " + (employee1 == employeeDup));
System.out.println("employee1.equals(employeeDup) => " + employee1.equals(employeeDup));
}
}
class Employee {
int employeeId;
String employeeName;
Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
Output:
employee1 == employee2 => true
employee1.equals(employee2) => true
employee1 == employeeDup => false
employee1.equals(employeeDup) => false
You will get the same results when comparing two objects using == and equals methods if you do not override the equals method.
✏️ Always compare two objects (created using the new keyword) using the equals(Object obj) method and by overriding it in your class.
In our example, we say that two employees are the same if their name and id are the same,
Example: override equals method@Override
public boolean equals(Object obj) {
//If object is null then they are not same
if(obj == null) return false;
//If object is have the same reference they are same
if(obj == this) return true;
Employee employee = (Employee) obj;
return this.employeeId == employee.employeeId &&
this.employeeName.equals(employee.employeeName);
}
Output:
employee1 == employee2 => true
employee1.equals(employee2) => true
employee1 == employeeDup => false
employee1.equals(employeeDup) => true
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python] - Python
- Enable Dark Mode in Gmail Desktop Browser - Google
- Install Microsoft Remote Desktop (RDP) Client on Mac - Microsoft
- Android EditText Cursor Colour appears to be white - Android
- Steps to Kill a Running Process in Ubuntu Linux - Ubuntu
- Google Local Guide Program and Perks of Contributing to Google Maps - Google
- Java 8: Convert Stream to Array - Java
- [Fix] Docker Error response from daemon: manifest for :latest not found: manifest unknown - Docker