The equals()
method is a static method of the Objects
class that accepts two objects and checks if the objects are equal.
null
, then equals()
returns true
.null
, then equals()
returns false
.equals()
returns true
.equals
method of the first argument to determine equality.To learn more about the
equals
method of theObjects
class, refer here.
public static boolean equals(Object a, Object b)
Object a
: first object.
Object b
: second object.
The method returns true
if the objects are equal; otherwise, equals
returns false
.
In the code below, we pass null
as an argument to the equals
method. The method should return true
, as both the input objects are null
.
import java.util.Objects;public class main {public static void main(String[] args) {boolean equalityCheck = Objects.equals(null, null);System.out.println("The Objects.equals() method returns '" + equalityCheck + "' when the passed objects are null");}}
In the code below, we pass null
as one of the arguments for the method. The method should return false
, as one of the input objects is null
.
import java.util.Objects;public class main {public static void main(String[] args) {boolean equalityCheck = Objects.equals(null, 4);System.out.println("The Objects.equals() method returns '" + equalityCheck + "' when null is passed as the first object.");equalityCheck = Objects.equals(4, null);System.out.println("The Objects.equals() method returns '" + equalityCheck + "' when null is passed as the second object.");}}
In the code below, we define a class Temp
with attributes a
and b
. The methods toString()
, hashCode
, and equals
are overridden in the class that has custom implementation.
Here, the equals
method is overridden in the Temp
class and checks if the objects have the same values for the attributes a
and b
.
Temp
class, temp1
, temp2
, and temp3
.temp1
and temp2
have the same values for the attributes a
and b
. Hence, passing temp1
and temp2
as parameters to the method should return true
, as the values of the attributes of the objects are equal.temp2
and temp3
have different values for the attributes a
and b
. Hence, passing temp2
and temp3
as parameters to the method should return false
, as the values of the attributes of the objects are not equal.import java.util.Objects;public class main {static class Temp{private int a, b;public Temp(int a, int b) {this.a = a;this.b = b;}@Overridepublic String toString() {return "Temp{" +"a=" + a +", b=" + b +'}';}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Temp temp = (Temp) o;return a == temp.a && b == temp.b;}@Overridepublic int hashCode() {return Objects.hash(a, b);}}public static void main(String[] args) {Temp temp1 = new Temp(2,3);Temp temp2 = new Temp(2,3);Temp temp3 = new Temp(5,4);System.out.println(Objects.equals(temp1, temp2));System.out.println(Objects.equals(temp2, temp3));}}