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
- Add two numbers using Java Generics
- Convert Java List to Json String using Jackson
- Convert Java Object to JSON using Jackson Library
- Java SE JDBC: Insert with PreparedStatement Example
- [Program] How to read three different values using Scanner in Java
- Java JDBC Batch Update Example with PreparedStatement
- Java Stream flatmap() Examples
- Save Java Object as JSON file using Jackson Library
- Java get day of the week as an int using DayOfWeek
- Create Nested Directories using Java Code
- Java JDBC Delete a Record in Database Table using PreparedStatement
- List of jars required for Struts2 project
- Convert Java Object to XML using Jackson Library
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Java JDBC Get Id of the Inserted Record with AutoIncrement
- How to list all tables using Java JDBC
- Java Jackson ObjectMapper Class with Examples
- Fix: Maven - Failed to execute goal - Compilation failure - Source/Target option 5 is no longer supported. Use 7 or later
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Formatting Double in Java [Examples]
- How to run Java Unit Test cases with Apache Maven?
- [fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring
- [Fix] java: integer number too large compilation error
- [Java] Read a File with UTF-8 Encoding
- How to detect Operating System using Java code
- cURL HTTP GET request command examples - HowTos
- Fixing Android unknown error 961 while downloading app - Android
- Android Studio emulator/Device logCat logs not displayed - Android-Studio
- Fetch only content-type using cURL Command - cURL
- fatal: Unable to create '/c/git_repo/.git/index.lock': File exists. If no other git process is currently running, this probably means a git process crashed in this repository earlier. - Git
- Android Launch! The connection to adb is down, and a severe error has occured - Android
- Install Java Runtime Environment (Oracle or open JRE) on Ubuntu - Linux
- How to uninstall GarageBand from Mac - MacOS