I generally use a static utility function that I wrote called equalsWithNulls to solve this issue:

class MyUtils {
  public static final boolean equalsWithNulls(Object a, Object b) {
    if (a==b) return true;
    if ((a==null)||(b==null)) return false;
    return a.equals(b);
  }
}

Usage:

if (MyUtils.equalsWithNulls(s1,s2)) {
  // do stuff
}

Advantages of this approach:

  • Wraps up the complexity of the full equality test in a single function call. I think this is much better than embedding a bunch of complex boolean tests in your code each time you do this. It's much less likely to lead to errors as a result.
  • Makes your code more descriptive and hence easier to read.
  • By explicitly mentioning the nulls in the method name, you convey to the reader that they should remember that one or both of the arguments might be null.
  • Does the (a==b) test first (an optimisation which avoids the need to call a.equals(b) in the fairly common case that a and b are non-null but refer to exactly the same object)
Answer from mikera on Stack Overflow
🌐
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 - This is because, in the if condition, you are first using the unknown string’s equals method to compare the other string. In this case, the unknown string is null, which means it doesn’t exist. Thus a NullPointerException.
Discussions

Java comparison == is not null-safe?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
41
16
February 21, 2024
Java null check why use == instead of .equals() - Stack Overflow
In Java I am told that when doing a null check one should use == instead of .equals(). What are the reasons for this? More on stackoverflow.com
🌐 stackoverflow.com
How do I compare a generic type with null in java?
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. More on reddit.com
🌐 r/learnprogramming
3
3
February 6, 2023
Need some help debugging. Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.equals(Object)" because "this.items[i]" is null
items[size + 1] = value; Don't add 1 here, use: items[size] = value; Arrays are 0-indexed in java, so you want to fill in the 0'th element; if you start from 1 (as you do here), items[0] will always be null. You can actually use the postfix ++ here like this and combine this line with the next: items[size++] = value; This will set items[0] to value and then increment size to 1 the first time. More on reddit.com
🌐 r/javahelp
5
2
July 23, 2023
🌐
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.
🌐
JoeHx Blog
joehxblog.com › does-null-equal-null-in-java
Does Null Equal Null in Java? – JoeHx Blog
October 31, 2018 - true: true false: false null == null: true string == null: true number == null: true Objects.equals(null, null): true Objects.equals(string, null): true Objects.equals(number, null): true Objects.equals(string, number): true · The first two outputted lines were just to get a feel as to how Java outputs the raw boolean values true and false. Everything here pretty much is as expected; the only lines that I find interesting is the output I commented out:
🌐
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
🌐
Qlik Community
community.qlik.com › t5 › Talend-Studio › Handling-nulll-while-doing-equals-function › td-p › 2326825
Handling nulll while doing equals function - Qlik Community - 2326825
February 4, 2017 - As we know equals function (var1.equals(var2)) does not handle null values and it thows "null pointer exception ".In other words , both variables should have values only then it can work .If I used two equals function (==) function It is not ...
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

🌐
DeepSource
deepsource.com › directory › java › issues › JAVA-E0110
`equals` method does not handle null valued operands (JAVA-E0110) ・ Java
Python JavaScript Java Go C# Ansible AWS CloudFormation Linter C & C++ Dart Analyze Docker Kotlin KubeLinter PHP Ruby Rust Scala Secrets Shell Slither Solhint SQL Swift Terraform Test coverage · Audit: Biometric authentication should always be used with a cryptographic objectJAVA-A1030Non-constant string passed to `execute` or `addBatch` method on an SQL statementJAVA-S0082`equals` method does not handle null valued operandsJAVA-S0110Reference to mutable object which is returned may expose internal representation of dataJAVA-S0132Reference to externally mutable object stored as internal state
🌐
Coderanch
coderanch.com › t › 523760 › java › null-null-java
null==something vs something==null in java (Beginning Java forum at Coderanch)
January 16, 2011 - The short answer is that they are the same. The long answer is that this is a remains from the old C days where everything could be treated as a boolean. If you forgot one of the = signs you would get an assignment. With something = null that assignment would succeed and the result would be 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.
🌐
Educative
educative.io › answers › what-is-objectsequals-in-java
What is Objects.equals in Java?
If any one of the objects points to null, then equals() returns false. If both the objects are equal, then equals() returns true. Otherwise, we use the equals method of the first argument to determine equality.
🌐
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
Answer (1 of 7): I read everywhere responses like —picking randomly Lew Bloch answer : « variable == null reads naturally. The reverse does not. » and conclude. Yes, for most indo-european speaking language. You learn and formulate your thinking on your mother language as child.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Objects.html
Objects (Java Platform SE 8 )
October 20, 2025 - Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality.
🌐
Coderanch
coderanch.com › t › 545457 › java › comparing-values-equalsIgnoreCase-equals-NULL
comparing two values with equalsIgnoreCase and equals with NULL as first value. (Java in General forum at Coderanch)
July 14, 2011 - If one is null and other has values,if these are assigned at run time ; how do I compare with equalsIgnoreCase and equals() ? Apparently null is different from any other value,so I HAVE TO EXPECT null and other values in both elements. This happends for only first element. How do I write a refined code for comparing two values considering or expecting null ? if I use the following way,its not correct ... Find the java.util.Objects class, which has equals() methods overloaded to take two parameters, and can cope with null values.
🌐
GeeksforGeeks
geeksforgeeks.org › java › program-to-check-if-the-string-is-null-in-java
Program to check if the String is Null in Java - GeeksforGeeks
July 12, 2025 - To check if a string is null in Java, we can use the "==" operator that directly compares the string reference with null.
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - The equals() method of StringUtils class is an enhanced version of the String class method equals(), which also handles null values:
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
1 week ago - But that is rarely applicable in real-world applications. Now let’s suppose that we’re working with an API that cannot accept null parameters or can return a null response that has to be handled by the client. This presents the need for us to check the parameters or the response for a null value. Here, we can use Java Assertions instead of the traditional null check conditional statement:
🌐
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.
🌐
How to do in Java
howtodoinjava.com › home › string › java string.equals()
Java String.equals() with Examples - HowToDoInJava
January 9, 2023 - It returns true if and only if: ...quals(str2)); Assertions.assertFalse(str1.equals(str3)); The equals() does not support null argument and throws NullPointerException....