Java - equals() Method



Description

The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument. An object is first compared based on its type and then based on its value. For example, an Integer object with same value as of a Short object will be unequal and this method will return false as a result of comparing the two for equality.

Syntax

public boolean equals(Object o)

Parameters

Here is the detail of parameters −

  • Any object.

Return Value

  • The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.

Example 1

In this example, we're showing the usage of equals() method to compare int values. We've created three Integer variables x,y and z and initialized with int values. A Short variable is created with same value as x. Then using equals() methods, we're comparing each variables to cover various cases.

public class Test { 
   public static void main(String args[]) {
      Integer x = 5;
      Integer y = 10;
      Integer z = 5;
      Short a = 5;

      System.out.println(x.equals(y));  
      System.out.println(x.equals(z)); 
      System.out.println(x.equals(a));
   }
}

This will produce the following result −

Output

false
true
false

Example 2

In this example, we're showing the usage of equals() method to compare float values. We've created three Float variables x,y and z and initialized with float values. A Double variable is created with same value as x. Then using equals() methods, we're comparing each variables to cover various cases.

public class Test { 
   public static void main(String args[]) {
      Float x = (float)5.0;
      Float y = (float)10.0;
      Float z = (float)5.0;
      Double a = 5.0;

      System.out.println(x.equals(y));  
      System.out.println(x.equals(z)); 
      System.out.println(x.equals(a));
   }
}

This will produce the following result −

Output

false
true
false

Example 3

In this example, we're showing the usage of equals() method to compare double values. We've created three Double variables x,y and z and initialized with double values. A Float variable is created with same value as x. Then using equals() methods, we're comparing each variables to cover various cases.

public class Test { 
   public static void main(String args[]) {
      Double x = 5.0;
      Double y = 10.0;
      Double z = 5.0;
      Float a = (float)5.0;

      System.out.println(x.equals(y));  
      System.out.println(x.equals(z)); 
      System.out.println(x.equals(a));
   }
}

This will produce the following result −

Output

false
true
false
java_numbers.htm
Advertisements