Java Null Check: Why Use == Instead of .equals()

Nov 20, 2025 · Programming · 11 views · 7.8

Keywords: Java | null check | object comparison | NullPointerException | Objects.equals

Abstract: This article provides an in-depth analysis of why the == operator is preferred over the .equals() method for null checks in Java. It explores the fundamental differences between reference comparison and content equality, with detailed code examples illustrating NullPointerException mechanisms. The discussion includes Java 7's Objects.equals() as a safer alternative and contrasts with Kotlin's == operator behavior, offering comprehensive guidance on Java object comparison best practices.

Fundamental Differences Between Reference Comparison and Content Equality

In Java programming, the == operator and the .equals() method serve fundamentally different purposes. The == operator compares whether two variables reference the exact same object instance in memory, while .equals() checks whether two objects are logically equal according to their class's specific implementation of equality.

Critical Issues in Null Checking

When checking variables that might be null, using the == operator is the safe choice. This is because == directly compares reference values and will not throw an exception even if the variable is null. In contrast, .equals() is an instance method that must be invoked on an object instance. Attempting to call any method, including .equals(), on a null reference will result in a NullPointerException.

Code Example Analysis

Consider the following example code:

class Foo {
    private int data;

    Foo(int d) {
        this.data = d;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || other.getClass() != this.getClass()) {
           return false;
        }
        return ((Foo)other).data == this.data;
    }
}

Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances

System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition

Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it

System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything

System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null

Safe Comparison Methods Introduced in Java 7

Since Java 1.7, the java.util.Objects class provides the equals() static method, which safely handles comparisons between potentially null objects:

Objects.equals(onePossibleNull, twoPossibleNull)

This method internally handles null checks, eliminating the risk of NullPointerException and represents the recommended approach in modern Java development.

Comparison with Other Languages

It's important to note that different programming languages handle equality comparisons differently. In Kotlin, for example, the behavior of the == operator differs significantly from Java. In Kotlin, == compares the data content of two variables, equivalent to Java's .equals() method, while === is used for reference equality comparison. These design differences underscore the importance of understanding language-specific semantics.

Best Practice Recommendations

When performing null checks, always use the == operator or Objects.equals() method. If you must use the .equals() method, always perform a null check first:

if(str != null && str.equals("hi")){
 // str contains hi
}

This defensive programming habit effectively prevents runtime exceptions and enhances code robustness.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.