Why a.equals(b) Can Crash but Objects.equals(a,b) Won’t – Java Equality Explained
This article explains the differences between a.equals(b) and Objects.equals(a,b) in Java, covering null handling, empty‑string cases, source‑code analysis of java.util.Objects, and the distinction between reference (a==b) and logical (a.equals(b)) comparisons.
1. When values are null
1. a.equals(b) where a is null throws a NullPointerException.
2. a.equals(b) where a is not null but b is null returns false.
3. Objects.equals(a, b) returns true if both are null, returns false if exactly one is null, and never throws NullPointerException.
null.equals("abc") → throws NullPointerException
"abc".equals(null) → false
null.equals(null) → throws NullPointerException
Objects.equals(null, "abc") → false
Objects.equals("abc", null) → false
Objects.equals(null, null) → true2. When values are empty strings
If both a and b are empty strings ( ""), a.equals(b) returns true; otherwise it returns false. Objects.equals behaves identically.
"abc".equals("") → false
"".equals("abc") → false
"".equals("") → true
Objects.equals("abc", "") → false
Objects.equals("", "abc") → false
Objects.equals("", "") → true3. Source code analysis
Source
public final class Objects {
private Objects() {
throw new AssertionError("No java.util.Objects instances for you!");
}
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}Explanation
The method first checks reference equality ( a == b). If that fails, it ensures a is not null before invoking a.equals(b), which prevents a NullPointerException.
4. Difference between a == b and a.equals(b)
a == bcompares object references; it returns true only when both references point to the same heap object. a.equals(b) performs logical comparison based on the object's content; it can be overridden to provide meaningful equality semantics.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
