When Does a.equals(b) Throw? Understanding Java Null Handling and Objects.equals
This article explains how a.equals(b) behaves with null and empty strings, compares it to Objects.equals, analyzes the underlying source code, and clarifies the difference between reference comparison (a==b) and logical equality (a.equals(b)) in Java.
1. Null values
When a is null, calling a.equals(b) throws a NullPointerException. If a is non‑null and b is null, a.equals(b) returns false. Objects.equals(a, b) returns true only when both arguments are null, returns false when exactly one is null, and never throws an exception.
null.equals("abc") → throws NullPointerException
"abc".equals(null) → returns false
null.equals(null) → throws NullPointerException
Objects.equals(null, "abc") → returns false
Objects.equals("abc", null) → returns false
Objects.equals(null, null) → returns true2. Empty string values
If both a and b are empty strings ( ""), a.equals(b) returns true. If only one of them is empty, the result is false. Objects.equals exhibits the same behavior in these cases.
"abc".equals("") → returns false
"".equals("abc") → returns false
"".equals("") → returns true
Objects.equals("abc", "") → returns false
Objects.equals("", "abc") → returns false
Objects.equals("", "") → returns true3. Source code analysis
1. Source
public final class Objects {
private Objects() {
throw new AssertionError("No java.util.Objects instances for you!");
}
/**
* Returns {@code true} if the arguments are equal to each other
* and {@code false} otherwise.
* Consequently, if both arguments are {@code null}, {@code true}
* is returned and if exactly one argument is {@code null}, {@code false}
* is returned. Otherwise, equality is determined by using the
* {@link Object#equals} method of the first argument.
*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}2. Explanation
The method first checks reference equality with a == b. If that is true, it returns true immediately. If not, it ensures a is not null before invoking a.equals(b), which prevents a NullPointerException when only one argument is null.
4. Difference between a==b and a.equals(b)
a==bcompares the two object references; it yields true only when both references point to the exact same object in memory. a.equals(b) performs logical equality, which can be overridden by a class to compare the internal state of objects, and returns true when the objects are considered equal according to that logic.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
