Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

java.util.Objects — validation, equality, and hashing

Learn Objects.requireNonNull, Objects.equals, and Objects.hash: null checks, equality for nullable references, and computing a hash from fields.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

import java.util.Objects;
Objects.requireNonNull(value, "value");
Objects.equals(a, b);
Objects.hash(field1, field2);

java.util.Objects provides static utility methods. Entry scope: Java SE 21; the repository runtime and production runtime have not been attested.

Objects.requireNonNull(value, "value") returns the same reference or throws NullPointerException with the supplied message. It is useful for parameter validation but does not check, for example, whether a string is empty.

Objects.equals(a, b) returns true if both arguments are null and false if only a is null. When a is non-null, equality is determined by the first argument's equals method. If a == b and both references point to the same object, the Java SE 21 API does not guarantee that the call to a.equals(b) is skipped. The method does not compare array contents.

Objects.hash(field1, field2) hashes a sequence like Arrays.hashCode(Object[]). When implementing hashCode(), use fields consistent with equals(): equal objects must have equal hashes, but collisions are possible. Objects.hash(x) is not a replacement for Objects.hashCode(x) for a single object.

Examples

import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        String name = Objects.requireNonNull("Ada", "name");
        System.out.println(name);
        System.out.println(Objects.equals(null, null));
        System.out.println(Objects.equals(name, null));
        System.out.println(Objects.hash(1, 2));
        try {
            Objects.requireNonNull(null, "name");
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}

Result

Ada
true
false
994
name

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources