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
🌐
Medium
medium.com › @muqsithirfan › java-null-comparison-fcfbcb55ac67
Java NULL comparison. While working in Java projects I… | by Muqsith Irfan | Medium
March 25, 2017 - Java NULL comparison While working in Java projects I sometimes used to see my colleagues writing code for null comparison as if ( null == object) { … I used to wonder why would someone compare …
🌐
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
🌐
Reddit
reddit.com › r/learnprogramming › how do i compare a generic type with null in java?
r/learnprogramming on Reddit: How do I compare a generic type with null in java?
March 21, 2023 -

I've already discovered that comparing a generic type requires you to use an int to restore the value of compareTo, but if I'm trying to check if T value == Null, java throws an error stating that the compareTo (null) method is undefined for type T.

the code I have so far is

int cmp;
if(cmp = tree.get(index).compareTo(null) == 0)

to check if the value at the index of tree == null.

Thanks in advance :)

edit: well, I actually just fixed it by deleting cmp XD

Top answer
1 of 2
2
You’re probably doing it wrong; usually you want to use some method like contains to check whether something’s not in a collection, and compareTo(null) and equals(null) are bad mojo to begin with. Syntactically, Java’s complaining because it’s breaking the text down as if(cmp = (tree.….compareTo(null) == 0)) with tree.….compareTo(null) == 0 being assigned to cmp, and if testing the value that was assigned. But == 0 provides a boolean, not an int, so you can’t assign anything==anything to cmp; and then if expects a boolean or unboxed Boolean, not an int, so that’s also invalid. If you want to save compareTo’s result en passant, you need a pair of parens around the first part, if((cmp = tree.get(index).compareTo(null)) == 0) ↑here and here↑. Now the relational result from compareTo (an actual int) is saved to cmp, and that same value is compared against 0, producing a boolean for if to consume. Fundamentally, though, compareTo and equals describe bivalent relationships which break if you try to use null in there. For example, a.compareTo(b) represents a query of whether a ⋚ b, and therefore also whether b ⋛ a, and therefore any value of a should be able to be used in b’s place and vice versa. Similarly, a.equals(b) represents a query of whether a = b, and therefore also whether b = a. So let’s play with those identities. if(tree.get(index).compareTo(null) == 0) That looks just fine; we pass null as the argument to compareTo. But changing to the ostensibly-equivalent condition if(null.compareTo(tree.get(index)) == 0) is fully illegal; null doesn’t name a specific enough type to actually find a Comparable.compareTo implementation, and even if it were specific enough, that method would be given null for its this argument, which is illegal for non-static methods and must result in a NullPointerException being thrown. Similarly, if(tree.get(index).equals(null)) is syntactically valid, but if we flip it using the semantic identity, if(null.equals(tree.get(index))) we again have a problem: null would necessarily have an equals method if it named an object, but null contributes no vtable and thus no means of determining how to actually carry out equals’ execution. (Any type’s equals might be chosen with equal correctness, including the equals of an as-yet-nonexistent type.) And of course, trying to ((Foo)null).equals(…) would trigger a NullPointerException unless you’ve found your way to a static equals method. ( java.util.Objects ’ methods can be used when you really do want to involve null more safely in compareTo, equals, and other basic methods, although compare can still throw.) So what you almost always want is either the collections .contains or .containsKey method, which directly checks whether something’s in there, or if your collection is actually permitted to contain null (really don’t, because you can’t tell whether X{k}=null or k∉X), you want to == null or != null directly.
2 of 2
1
isNull() maybe?
🌐
Medium
medium.com › @AlexanderObregon › javas-objects-compare-method-explained-7a9ccda5ea74
Java’s Objects.compare() Method Explained | Medium
December 13, 2024 - The Objects.compare() method in Java is a utility that simplifies the process of comparing two objects by utilizing a specified Comparator. It is particularly useful for handling scenarios where objects being compared may include null values. ...
🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
October 10, 2025 - ... String a = new String("Hello!"); ... 7, when Objects#equals appeared · Now let’s compare object order with the ObjectUtils#compare method....
Find elsewhere
🌐
Quora
quora.com › What-is-a-better-syntax-in-Java-obj-null-or-null-obj-when-checking-if-an-object-exists
What is a better syntax in Java: 'obj == null' or 'null == obj', when checking if an object exists? - Quora
Java disallows assignment of non-boolean to boolean contexts, so "if (obj = null)" is a compile error. Thus flipping operands gives no reliability benefit. ... In rare stylistic contexts (e.g., generated code, ported C code) you may see "null == obj". It’s acceptable but uncommon in Java. ... Prefer "obj == null" for clarity, convention, and maintainability. Use explicit Objects.isNull(obj) only when emphasizing functional style or when using method references; otherwise, the simple equality check is best.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Objects.html
Objects (Java Platform SE 8 )
1 week ago - This value can be computed by calling hashCode(Object). ... Returns the result of calling toString for a non-null argument and "null" for a null argument. ... Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise. ... the result of calling toString on the first argument if it is not null and the second argument otherwise. ... Returns 0 if the arguments are identical and c.compare(a, b) otherwise.
🌐
Coderanch
coderanch.com › t › 396208 › java › null-comparison
null comparison (Beginning Java forum at Coderanch)
... Hi Tyler, Compare null values are null do the following instead of using the equals method: if (ipArray[s] == null) //is null if(ipArray[s] != null) // if not null. You can't do: ipArray[s].equals(null) as there is no instance created for the value so there will not be a pointer to the object.
🌐
TutorialsPoint
tutorialspoint.com › comparing-strings-with-possible-null-values-in-java
Comparing Strings with (possible) null values in java?
In the same way the equals() method of the object class accepts two String values and returns a boolean value, which is true if both are equal (or, null) and false if not. import java.util.Scanner; public class CompringStrings { public static void main(String args[]) { Scanner sc = new ...
🌐
Coderanch
coderanch.com › t › 375244 › java › compareTo-null-Date-object
compareTo with null Date object (Java in General forum at Coderanch)
The sort() method will call compareTo() on objects in the list without checking for null first. You have two basic choices - either remove the nulls from the list (maybe re-adding them later after the list is sorted, if you really want to have them there) - or sort the list yourslef, without using Collections.sort().
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