• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Selenium
  • Manual Testing
  • SQL Tutorial For Beginners
  • Difference
  • Tools
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » Equals Method Java

Equals Method Java

Last Updated on: April 22, 2023 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Equals Method In Java
  • How to User Equals() Method In Java String Class?
  • Equals() Method In Java Numeric Data Types
  • Override Java Equals Method

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 equals method is basically a part of the object class, and the object class basically 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.

The “equals” method is often overridden in Java 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 which 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 to User Equals() Method In Java String Class?

The above program shows that when two String objects are compared using the equals () method, it returns a result of true or false 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, so without wasting much more time, let me go to the below program.

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.

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers