Java Utility Library

Java Objects - equals() Method



The java.util.Objects.equals() method is used to compare the given two objects. It returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.

Syntax

public static boolean equals(Object a,
                             Object b)

Parameters

a Specify an object.
b Specify an object to be compared with a for equality.

Return Value

Returns true if the arguments are equal to each other and false otherwise.

Exception

NA

Example:

In the example below, the java.util.Objects.equals() method is used to compare the given objects.

import java.util.*;

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(Objects.equals(obj1, obj2));

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

The output of the above code will be:

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

❮ Java.util - Objects