Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.

If both objects are null, it will return true, if one is null and the other isn't, it will return false. Otherwise, it will return the result of calling equals on the first object with the second as argument.

Answer from Mark Rotteveel on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Objects.html
Objects (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects. ... Returns true if the arguments are equal ...
🌐
Medium
medium.com › @AlexanderObregon › javas-objects-equals-method-explained-3a84c963edfa
Java’s Objects.equals() Method Explained | Medium
4 days ago - The Objects.equals() method makes object comparisons in Java easier while handling null values safely. It helps prevent NullPointerException, keeps code readable, and makes equality checks more reliable.
🌐
Medium
medium.com › @thilinajayawardana_85346 › java-string-nullpointerexception-safe-equals-check-404481934e9b
Java String NullPointerException safe equals check | by Thilina Jayawardana | Medium
June 30, 2020 - In that case, you are always invoking the equals method of a String that you are pretty sure it exists. Usually, it could be a constant or a new String object. If you are not really sure either of them exists, so you better to check for null for the String that you are trying to invoke the equals method of.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › class
Null safe equals method - Java Code Geeks
July 21, 2013 - If the given object is also instance of A and its fields are equal to the object’s fields, then true is returned. We create two new instances of A, with different parameters and call the nullSafeEquals(Object o1, Object o2) method, in class NullSafeEquals that extends ObjectUtils, ... package com.javacodegeeks.snippets.core; import java.util.Arrays; abstract class ObjectUtils { private static final int INITIAL_HASH = 7; private static final int MULTIPLIER = 31; private static final String EMPTY_STRING = ""; private static final String NULL_STRING = "null"; private static final String ARRAY_START = "{"; private static final String ARRAY_END = "}"; private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END; private static final String ARRAY_ELEMENT_SEPARATOR = ", "; /** * Determine if the given objects are equal, returning true if both are null * or false if only one is null.
🌐
Blogger
marxsoftware.blogspot.com › 2021 › 02 › java-nullpointerexception-avoidance-and.html
Inspired by Actual Events: Java NullPointerException Avoidance and Enhancement Tactics
When we know that at least one of two objects being compared is definitely NOT null, we can safely compare the two objects (even if the other one may be null), by calling Object.equals(Object) against the known non-null object.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › equals
Java String equals() - Compare Strings Equality
December 23, 2024 - String str1 = null; String str2 ... comparing. The second approach utilizes the Objects.equals() method, which is null-safe and eliminates the need for explicit null checks....
Find elsewhere
Top answer
1 of 16
213

They're two completely different things. == compares the object reference, if any, contained by a variable. .equals() checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals is a method, if you try to invoke it on a null reference, you'll get a NullPointerException.

For instance:

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;
    }

    /* In a real class, you'd override `hashCode` here as well */
}

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
2 of 16
52

In addition to the accepted answer (https://stackoverflow.com/a/4501084/6276704):

Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:

Objects.equals(onePossibleNull, twoPossibleNull)

java.util.Objects

This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

Since: 1.7

🌐
Blogger
tjisblogging.blogspot.com › 2020 › 06 › java-string-nullpointerexception-safe.html
Java String NullPointerException safe equals check
if (theStringIknow.equals(someString)) { System.out.println("Same same"); } In that case, you are always invoking the equals method of a String that you are pretty sure it exists. Usually, it could be a constant or a new String object. If you are not really sure either of them exists, so you better to check for null for the String that you are trying to invoke the equals method of.
🌐
Educative
educative.io › answers › what-is-objectsequals-in-java
What is Objects.equals in Java?
In the code below, we pass null as one of the arguments for the method. The method should return false, as one of the input objects is null. ... System.out.println("The Objects.equals() method returns '" + equalityCheck + "' when null is passed as the first object.");
🌐
LabEx
labex.io › tutorials › java-how-to-handle-integer-null-comparison-437111
How to handle Integer null comparison | LabEx
At LabEx, we recommend developers understand these nuanced behaviors to write more defensive and predictable Java code. When working with Integer objects, developers must be cautious about null comparisons to prevent NullPointerException. public boolean safeCompare(Integer a, Integer b) { return Objects.equals(a, b); }
🌐
Codemia
codemia.io › knowledge-hub › path › compare_two_objects_in_java_with_possible_null_values
Compare two objects in Java with possible null values
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Piotr Horzycki
peterdev.pl › 2019 › 08 › 09 › defensive-coding-null-safe-string-comparisons
Defensive coding: Null-safe string comparisons | Piotr Horzycki - Java and PHP developer’s blog
August 9, 2019 - So if we want to compare a variable to a string literal, let’s use the null-safe style proposed in the second listing above. https://stackoverflow.com/questions/43409500/compare-strings-avoiding-nullpointerexception/43409501 · https://softwareengineering.stackexchange.com/questions/313673/is-use-abc-equalsmystring-instead-of-mystring-equalsabc-to-avoid-null-p · https://www.javacodegeeks.com/2012/06/avoid-null-pointer-exception-in-java.html
🌐
Kotlin
kotlinlang.org › docs › null-safety.html
Null safety | Kotlin Documentation
In Java, this would be the equivalent of a NullPointerException, or an NPE for short. Kotlin explicitly supports nullability as part of its type system, meaning you can explicitly declare which variables or properties are allowed to be null.
🌐
TechVidvan
techvidvan.com › tutorials › java-string-equals-method
Java String equals() Method - TechVidvan
March 18, 2024 - Overriding:In user-defined classes, the equals() method is frequently changed to implement unique comparison logic. Null Safety: If you try to use equals() on a null reference, it will return false rather than throwing an exception.
🌐
Errorprone
errorprone.info › bugpattern › EqualsNull
EqualsNull
This check replaces x.equals(null) with x == null, and !x.equals(null) with x != null. If the author intended for x.equals(null) to return true, consider this as fragile code as it breaks the contract of Object.equals(). See Effective Java 3rd Edition §10: Objey the general contract when overriding equals for more details.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java NullPointerException Avoidance and Enhancement Tactics - Java Code Geeks
March 1, 2021 - Placing the known non-null object on the left side of the .equals(Object) call is a general null-safe tactic for any object of any type. For String in particular, there are times when we want a null-safe way to compare two strings without regard ...