Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Objects.equals()

Compares two objects with equals(), safely for null.

Available since: Java 7

Syntax

static boolean equals(Object a, Object b)

Parameters

ParameterTypeDescription
aObjectThe first object; may be null.
bObjectThe second object; may be null.

Return value

booleantrue if both are null or a.equals(b).

Examples

No NullPointerException:

void main() {
    String a = null;
    String b = "Anna";
    IO.println(Objects.equals(a, b));
    IO.println(Objects.equals(null, null));
    IO.println(Objects.equals("Anna", b));
}

Output:

false
true
true

Notes

Handy in your own equals() when fields may be null: Objects.equals(email, other.email). For arrays it compares references — use Arrays.equals().

See also

  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.
  • String.equals() — Compares the contents of two strings.
  • Objects.isNull() — Checks whether a value is null; its partner nonNull() does the opposite.

Related recipes

In the tutorial

  • Methods of the Object class — The toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.

Thanks for reading!

Donate to the site — we work hard for you.