Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Objects.equals: null-safe object equality

Use `Objects.equals(a, b)` to compare objects according to their `equals` rules, even when one or both arguments may be `null`.

Version: Java SE 21

Syntax

import java.util.Objects;

// Java SE 21 API signature: public static boolean equals(Object a, Object b)
boolean equal = Objects.equals(a, b);

Objects.equals(a, b) is a static method in java.util.Objects that returns a boolean. In OpenJDK 21, if a == b, the method returns true without calling a.equals(b). This covers both references to the same object and two null arguments. If a == b is false, the method returns false when a is null; otherwise, it calls a.equals(b) and returns the result. When that call is made with b as null, the equals contract requires false. Unlike a direct call to a.equals(b), this method does not throw a NullPointerException just because a is null.

For two references, == is true when both refer to the same object or both are null. It does not compare contents. When Objects.equals calls a.equals(b), it uses the equality rule defined by the class of a. For example, String.equals compares character sequences, while the inherited Object.equals implementation checks only object identity.

If a.equals(b) is called, Objects.equals does not fix a faulty equals implementation or catch exceptions it throws. Objects.equals does not compare array elements; use Objects.deepEquals(a, b) when you want to compare array contents, including nested arrays.

Examples

import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        String a = "Java";
        String b = new String(a);

        System.out.println(Objects.equals(a, b));
        System.out.println(a == b);
        System.out.println(Objects.equals(null, null));
        System.out.println(Objects.equals(null, b));
        System.out.println(Objects.equals(a, null));
    }
}

Result

true
false
true
false
false

`new String(a)` creates a distinct `String` object with the same text, so `Objects.equals(a, b)` is `true` while `a == b` is `false`. The last three lines show the result for two `null` arguments and for a single `null` in each of the two positions.

Related lessons

  • Java · Lesson 28 · Intermediate · Version: 2

Sources