Understanding Equals Method and == Operator in Java

Introduction

In this article we will learn about how equals() and == work and when to use each of them, The concept of equality is an essential part of programming, and it's crucial to understand the differences between the equals() method and the == operator. While both are used to compare objects or values, they work differently depending on the context.

Working with equals() Method

equals() method is a method defined in the Object class, which is the root of all classes in Java. It is used to compare the content or state of two objects. By default, the equals() method in the Object class performs a reference comparison, which means it checks if two object references point to the same object in memory. However, most classes in Java override the equals() method to provide a more meaningful comparison based on the object's state or content. For example, the String class overrides the equals() method to compare the character sequences of two strings.

String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java"); // creating a new String object 

System.out.println(str1.equals(str2)); // OP: true
System.out.println(str1.equals(str3)); // OP: true

In the above example, str1 and str2 are equal because they refer to the same string literal in the string pool. str3 is a new String object created with the same character sequence as str1.equals(str3) returns true because the equals() method in the String class compares the character sequences.

Working with == Operator

The == operator is used to compare the references of objects or primitive values. When comparing objects with ==, it checks if the two object references point to the same object in memory.

String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java"); // Creating a new String Object

System.out.println(str1 == str2); // Op: true
System.out.println(str1 == str3); // Op: false

In the above example, str1 == str2 returns true because both str1 and str2 refer to the same string in the string pool. However, str1 == str3 returns false because str3 is a new String object created in the heap, and it has a different reference than str1 and str2. When comparing primitive data types like int, double, or boolean, the == operator compares their values directly.

Summary

In Java, the equals() method and the == operator have different purposes when it comes to comparing objects or values. The equals() method compares the content or state of objects, while the == operator compares the references of objects or the values of primitive data types. It's important to understand the differences between equals() and == and use them perfectly based on our requirements. When comparing objects for equality, it's generally recommended to use the equals() method unless you specifically need to check if two object references point to the same object in memory.


Similar Articles