Objects.equals()
Compares two objects with equals(), safely for null.
Available since: Java 7
Syntax
static boolean equals(Object a, Object b)Parameters
| Parameter | Type | Description |
|---|---|---|
| a | Object | The first object; may be null. |
| b | Object | The second object; may be null. |
Return value
booleantrue if both are null or a.equals(b).
Examples
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
trueNotes
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.