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
- [Fix] java.time.zone.ZoneRulesException: Unknown time-zone ID
- Parse XML file in Java using DOM Parser
- Java equals method - Tutorial
- [Program] How to read three different values using Scanner in Java
- Java: The value of the local variable string is not used
- Display Output in Java Console as a Table
- How to detect Operating System using Java code
- Java 8 Streams map() with examples
- [Fix] java: incompatible types: incompatible parameter types in lambda expression error
- Add newline character Java code example (\r \n \r\n)
- List of Java Major Minor Version Numbers
- IntelliJ Keyboard Shortcut to remove unused imports [Java]
- Java - Check if array contains the value
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- How to declare and initialize Array in Java Programming
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- XmlRpcException ConnectException connection refused error
- Create a Zip file using Java Code programmatically
- List of jar files for Jax-ws (SOAP) based Java Web Services
- How to fix Java HTTP java.net.UnknownHostException
- List of jars required for Struts2 project
- [fix] java: incompatible types: double cannot be converted to java.lang.Integer Generics
- Maven BUILD FAILURE: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
- Get the current timestamp in Java
- java: unclosed string literal [Error]
- SharePoint 2016 error - Could not find file ManageUserProfileServiceApplicationTenantSimplified.xml - SharePoint
- What does -Xms and -Xmx stands for in Java? - Java
- Android Studio Native typeface cannot be made error - Android
- How to stop or quit cat command? - HowTos
- Facebook : Warning: Request without access token missing application ID or client token - Facebook
- PHP 301 Redirect Permanently - PHP
- What is BTS? What is BTS A.R.M.Y? What is its meaning? - BTS
- Convert String to int in Java - Java