Fundamentals 5 min read

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.

Programmer DD
Programmer DD
Programmer DD
Why a.equals(b) Can Crash but Objects.equals(a,b) Won’t – Java Equality Explained

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) → true

2. 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("", "")    → true

3. 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 == b

compares 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavanullpointerexceptionObject EqualityObjects.equalsa.equalsJava 1.7
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.