Objects.equals: Null-Safe Comparison Utility
What you'll learn: How to use Objects.equals to compare objects safely without worrying about NullPointerException.
The Problem with Calling equals on null
You've learned that calling .equals() on a reference requires careful null checking. If you write obj1.equals(obj2) and obj1 is null, you'll get a NullPointerException. This forces you to write defensive code:
if (obj1 != null && obj1.equals(obj2)) {
// safe comparison
}
But what if both could be null? Your logic gets messy quickly.
The Objects.equals Solution
Java provides Objects.equals(a, b) as a utility method that handles all null cases automatically:
Objects.equals(obj1, obj2)
How it works:
- If both are
null, returnstrue(two nulls are considered equal) - If only one is
null, returnsfalse - If neither is
null, callsobj1.equals(obj2)safely
Practical Example
String name1 = null;
String name2 = null;
String name3 = "Alice";
// Safe comparisons without null checks
Objects.equals(name1, name2); // true (both null)
Objects.equals(name1, name3); // false (one null)
Objects.equals(name3, "Alice"); // true (normal equals)
This is especially useful when comparing object fields that might be optional (nullable).
Analogy
Think of Objects.equals as a diplomatic referee who knows how to handle empty chairs. If two chairs are empty, they're "equal" in their emptiness. If only one is empty, they're different. If both are occupied, the referee asks the occupants if they're equal.
Key Takeaway:
Use Objects.equals(a, b) for null-safe comparisons that automatically handle all null cases, eliminating the need for manual null checks before calling equals.