Equals Method Java

Java Equals Method Override: Welcome, all of you, to another blog post of the Java Tutorial series. In this blog post, we will talk about the equals method in Java programming language. So, the equals method is a part of the object class, and the object class provides many methods like equals and toString methods. It provides the hash code and many more methods as well. In the last blog post, we discussed using the toString method.

Now, let’s come back to the topic and try to understand what exactly the use of the equals method is.

Post Type:Core Java Tutorial
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Equals Method In Java

The “equals” method in Java is an essential concept for object-oriented programming. It is a method used to compare two objects for equality, and it is defined in the “Object” class, which is the root of the Java class hierarchy. The “equals” method compares the values of the object’s fields to determine whether they are equal.

Java often overrides the “equals” method to implement custom equality comparison logic for user-defined classes. Correctly implementing the “equals” method is crucial to ensure the correctness of the code and prevent unexpected behavior.

This article will discuss the importance of Java’s “equals” method, its usage, and best practices for implementing it. We will also cover some common pitfalls and how to avoid them.

Syntax:

public boolean equals(Object anotherObject)

This method returns true if the specified other object is equal to this object. You can tell if two objects are equal by implementing an equivalence relation on objects that are non-null reference values.

package marketingcopy;
public class EqualsDemo1 
{
	public static void main(String[] args) 
	{
		String s1="SoftwareTestingo";  
		String s2="SoftwareTestingo";  
		String s3="SOFTWARETESTINGO";  
		String s4="SoftwareTestingo Blog";  
		System.out.println(s1.equals(s2));//true because content and case is same  
		System.out.println(s1.equals(s3));//false because case is not same  
		System.out.println(s1.equals(s4));//false because content is not same  

	}
}

Output:

true
false
false

How do you use the Equals() Method in Java String Class?

The above program shows that when two String objects are compared using the equals () method, it returns a true or false result based on the content of the String objects. This is because the String class has overridden the equals () method.

package com.softwaretestingo.basic;
public class EqualsDemo2 
{
	public static void main(String[] args) 
	{
		String Str1 = new String("HELLO");
		String Str2 = new String("hello");    
		String Str3 = null;
		String Str4 = "HELLO";


		System.out.println("Check Weather Str1 and Str2 are equal : "+(Str1.equals(Str2)));  
		//Both Objects are Same
		System.out.println("Check Weather Str1 and Str4 are equal : "+(Str1.equals(Str4)));
		System.out.println("Check Weather Str2 and Str4 are equal : "+(Str2.equals(Str4)));
		System.out.println("Check Weather Str4 and Str3 are equal : "+(Str4.equals(Str3)));

	}
}

Output;

Check Weather Str1 and Str2 are equal : false
Check Weather Str1 and Str4 are equal : true
Check Weather Str2 and Str4 are equal : false
Check Weather Str4 and Str3 are equal : false

Equals() Method In Java Numeric Data Types

Java supports primitive data types like int, long, float, and double. If you want to create an object for one of the primitive data types, you can use a Wrapper class. For example, if you want to represent an int value as an object, you would use the Integer wrapper class. Similar wrapper classes exist for float values (Float), double values (Double), etc. These classes also have their own implementation of the equals method.

package com.softwaretestingo.basic;
public class EqualsDemo3 
{ 
	public static void main(String[] args) 
	{
	Long lng1 = 22l;
        Long lng2 = 22l;    
        Double dbl1 = 25.9d;
        Double dbl2 = 20.0d;
         
        System.out.println("Compare Two Long Values lng1 & lng2  : "+(lng1.equals(lng2)));  
        System.out.println("Compare Two Double  Values  dbl1 and dbl2 : "+(dbl1.equals(dbl2)));

	}
}

Output:

Compare Two Long Values lng1 & lng2  : true
Compare Two Double  Values  dbl1 and dbl2 : false

Override Java Equals Method

The examples above show us how to use the equals method in Java. But now we will try to understand how we can override the Equals method of the Java class with our own implementation.

So to explain this use of the equals method, let me create one scenario in front of you. Without wasting much more time, let me go to the program below.

package com.softwaretestingo.basic;
class Employee 
{ 
	private String name;
	private int age;
	Employee(String name, int age)
	{
		this.name = name;
		this.age = age;
	}
	// Overriding equals() to compare two objects
	public boolean equals(Object obj) 
	{
		// If We Compare with itself then it return true
		if (obj == this) 
		{
			return true;
		}
		// If obj object is instance of employee class then return false 
		if (!(obj instanceof Employee)) 
		{
			return false;
		}
		//typecast obj to Employee so that we can compare data members
		Employee emp = (Employee) obj;
		
		// Compare the data members and return accordingly
		return name.equals(emp.name)&& 
				Integer.compare(age, emp.age) == 0;
	}
}
public class EqualsExampleSample 
{
	public static void main(String[] args) {
		Employee emp1 = new Employee("Ramesh", 25);
		Employee emp2 = new Employee("Ramesh", 25);
		//Comparing the two objects
		boolean bool = emp1.equals(emp2);
		System.out.println(bool);
	}
}

Output:

true

Conclusion:

We have tried to explain the concept of the Java equals method in detail by taking various examples. But still, if you find any difficulties in understanding this important equals method concept, let us know in the comment section.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment