Java.lang.Object.equals() Method

Advertisements


Description

The java.lang.Object.equals(Object obj) indicates 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.

Declaration

Following is the declaration for java.lang.Object.equals() method

public boolean equals(Object obj)

Parameters

  • obj -- the reference object with which to compare.

Return Value

This method returns true if this object is the same as the obj argument; false otherwise.

Exception

  • NA

Example

The following example shows the usage of lang.Object.equals() method.

package com.tutorialspoint;

public class ObjectDemo {

   public static void main(String[] args) {

      // get an integer, which is an object
      Integer x = new Integer(50);

      // get a float, which is an object as well
      Float y = new Float(50f);

      // check if these are equal,which is 
      // false since they are different class
      System.out.println("" + x.equals(y));

      // check if x is equal with another int 50
      System.out.println("" + x.equals(50));

   }
}


Let us compile and run the above program, this will produce the following result:

false
true



Advertisements
Advertisements