Java Object equals()

The equals() method checks whether two objects are equal.

Example

class Main {
  public static void main(String[] args) {

    // create an object using Object class
    Object obj1 = new Object();

    // assign obj1 to obj2
    Object obj2 = obj1;

// check if obj1 and obj2 are equal System.out.println(obj1.equals(obj2));
} } // Output: true

Syntax of Object equals()

The syntax of the equals() method is:

object.equals(Object obj)

equals() Parameters

The equals() method takes a single parameter.

  • obj - object which is to be compared with the current object

equals() Return Values

  • returns true if two objects are equal
  • returns false if two objects are not equal

Note: In Java, if two reference variables refer to the same object, then the two reference variables are equal to each other.


Example 1: Java Object equals()

class Main {
  public static void main(String[] args) {

    // equals() method with Object class
    // create two objects
    Object obj1 = new Object();
    Object obj2 = new Object();

    // check if obj1 and obj2 are equal
System.out.println(obj1.equals(obj2)); // false
// assign obj1 to obj3 Object obj3 = obj1;
System.out.println(obj1.equals(obj3)); // true
} }

In the above examples, we have created objects of the Object class. Here, the equals() method is used to check if objects are equal to each other.


Example 2: Object equals() With String

class Main {
  public static void main(String[] args) {

    // equals() with String objects
    // create objects of string
    String obj1 = new String();
    String obj2 = new String();

    // check if obj1 and obj2 are equal
System.out.println(obj1.equals(obj2)); // true
// assign values to objects obj1 = "Java Programming"; obj2 = "Python Programming"; // again check if obj1 and obj2 are equal
System.out.println(obj1.equals(obj2)); // false
} }

In the above example, we have used the equals() method to check if two objects obj1 and obj2 are equal.

Here, initially, both the newly created objects are null. Hence, the method returns true. However, when we assigned values to the objects. The method returns false.

It is because the String class overrides the equal() method so that the method compares the element of the object. Since the values of obj1 and obj2 are different, the method returns false.

Note: The Object class is the superclass for all the classes in Java. Hence, every class and arrays can implement the equals() method.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges