Java
Null Values
Object Comparison
Programming
Coding Techniques

Compare two objects in Java with possible null values

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Java, object comparison becomes error-prone as soon as null is a possible value. The problem is not only avoiding NullPointerException; it is also being clear about what kind of comparison you mean. Most of the time, the right answer is Objects.equals(a, b), but understanding why that works makes it easier to choose the correct approach in more complex cases.

Use Objects.equals for Null-Safe Equality

The standard null-safe comparison helper is Objects.equals.

java
1import java.util.Objects;
2
3public class Main {
4    public static void main(String[] args) {
5        String a = null;
6        String b = null;
7        String c = "hello";
8
9        System.out.println(Objects.equals(a, b));
10        System.out.println(Objects.equals(a, c));
11        System.out.println(Objects.equals(c, "hello"));
12    }
13}

This method handles three important cases correctly:

  • both values are null,
  • one is null and the other is not,
  • and both are non-null and should be compared with equals.

That makes it the best default for ordinary equality checks.

Why a.equals(b) Is Risky

Calling a.equals(b) is only safe if you already know a is non-null.

java
1String a = null;
2String b = "hello";
3
4// a.equals(b); // throws NullPointerException

This is why so much older Java code is cluttered with manual null checks. Objects.equals exists specifically to remove that boilerplate and make the intention explicit.

Know the Difference Between == and equals

== compares references for objects, not semantic equality. For most domain objects, that is not what you want.

java
1String x = new String("hello");
2String y = new String("hello");
3
4System.out.println(x == y);
5System.out.println(x.equals(y));

Typical output is:

text
false
true

So the general rule is:

  • use == when you truly care whether both references point to the same object,
  • use equals or Objects.equals when you care about value equality.

Implement equals Carefully in Your Own Classes

If you compare custom objects, their class must implement equals consistently or your null-safe wrapper still will not give meaningful results.

java
1import java.util.Objects;
2
3class Person {
4    private final Integer id;
5    private final String name;
6
7    Person(Integer id, String name) {
8        this.id = id;
9        this.name = name;
10    }
11
12    @Override
13    public boolean equals(Object obj) {
14        if (this == obj) return true;
15        if (!(obj instanceof Person other)) return false;
16        return Objects.equals(id, other.id) && Objects.equals(name, other.name);
17    }
18
19    @Override
20    public int hashCode() {
21        return Objects.hash(id, name);
22    }
23}

Once equals is implemented well, comparing two Person objects with Objects.equals becomes straightforward.

Comparison for Ordering Is Different from Equality

Sometimes people say “compare” when they really mean “sort” or “order”. That is a different problem. For ordering with possible null values, use comparators such as Comparator.nullsFirst or Comparator.nullsLast.

java
1import java.util.Comparator;
2import java.util.List;
3
4List<String> values = List.of("beta", null, "alpha");
5values.stream()
6      .sorted(Comparator.nullsLast(String::compareTo))
7      .forEach(System.out::println);

This is not equality checking, but it is a common neighboring problem and it needs a different tool.

Prefer Clear Intent Over Clever Code

In code reviews, the best comparison code is usually the most explicit one. Objects.equals(a, b) immediately signals “null-safe equality”. That is better than a nested conditional or a one-liner that tries to be clever.

The same applies when comparing fields inside domain logic. Simpler null-safe code is easier to trust.

Common Pitfalls

  • Calling a.equals(b) when a may be null.
  • Using == for object equality when value equality is actually intended.
  • Forgetting to implement equals and hashCode properly in custom classes.
  • Confusing equality comparison with ordering or sorting.
  • Writing manual null-check ladders where Objects.equals already expresses the intent clearly.

Summary

  • 'Objects.equals(a, b) is the standard null-safe way to compare two Java objects for equality.'
  • Avoid calling a.equals(b) unless you know a is non-null.
  • Use == only for reference identity, not normal value equality.
  • Make sure custom classes implement equals and hashCode correctly.
  • Use comparator helpers for null-safe ordering, because ordering is a different problem from equality.

Course illustration
Course illustration

All Rights Reserved.