When Does a.equals(b) Throw NullPointerException? Understanding Java Equality
This article explains how Java handles null and empty‑string comparisons with a.equals(b), Objects.equals(a, b), and the == operator, detailing the resulting return values, exception behavior, and the underlying source code logic.
1. Cases When the Value Is null
When a is null and you call a.equals(b), a NullPointerException is thrown.
If a is not null but b is null, a.equals(b) simply returns false. Objects.equals(a, b) safely handles null: it returns true when both arguments are null, false when exactly one is null, and otherwise delegates to a.equals(b) without throwing 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. Cases When the Value Is an Empty String
If both a and b are empty strings ( ""), a.equals(b) returns true. If only one side is empty, the result is false. Objects.equals behaves identically in these scenarios.
"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 of Objects.equals
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.
* If both arguments are {@code null}, {@code true} is returned.
* If exactly one argument is {@code null}, {@code false} is returned.
* Otherwise equality is determined by using {@link Object#equals(Object)}.
*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}The method first checks reference equality ( a == b). If that fails, it ensures a is not null before delegating to a.equals(b), thereby avoiding 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 exact same object in memory. a.equals(b) performs a logical comparison based on the object's content. For meaningful equality checks, classes typically override equals to define what constitutes logical equivalence.
Java Architect Handbook
Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.
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.
