Java Utility Library

Java Object - equals() Method



The java.util.Object.equals() method is used to indicate whether some other object is "equal to" this one.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Syntax

public boolean equals(Object obj)

Parameters

obj Specify the reference object with which to compare.

Return Value

Returns true if this object is the same as the obj argument; false otherwise.

Exception

NA

Example:

In the example below, the java.util.Object.equals() method is used to compare the specified object with the given object.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    //creating Objects
    Object obj1[] = {25, 50, 75, 100};
    Object obj2[] = obj1;
    Object obj3[] = {10, 20, 30};
    
    //comparing obj1 and obj2
    System.out.print("Is obj1 equal to obj2: ");
    System.out.println(obj1.equals(obj2));

    //comparing obj1 and obj3
    System.out.print("Is obj1 equal to obj3: "); 
    System.out.println(obj1.equals(obj3)); 
  }
}

The output of the above code will be:

Is obj1 equal to obj2: true
Is obj1 equal to obj3: false

❮ Java.lang - Object