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
Answer from T.J. Crowder on Stack Overflow
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

🌐
JoeHx Blog
joehxblog.com › does-null-equal-null-in-java
Does Null Equal Null in Java? – JoeHx Blog
October 31, 2018 - Java doesn’t allow a direct equality check between two dissimilar objects; however, I found that if I typecast one of the objects to Object, then Java states that the two objects are equal: // Output: (Object)string == number: true System.out.println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java?
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
Best way to handle nulls in Java? - Software Engineering Stack Exchange
I have some code that is failing because of NullPointerException. A method is being called on the object where the object does not exist. However, this led me to think about the best way to fix t... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 23, 2011
Java null.equals(object o) - Stack Overflow
Does the (a==b) test first (an ... call a.equals(b) in the fairly common case that a and b are non-null but refer to exactly the same object) ... Sign up to request clarification or add additional context in comments. ... Thanks for the solution and the explication. 2012-06-13T09:50:24.65Z+00:00 ... Note that since Java 7 this method ... More on stackoverflow.com
🌐 stackoverflow.com
Java equals() selection
In Java, if I try to do.equals() on a null string, a null pointer error is issued. I’m wondering whether I can perform the following if I’m attempting to compare if a string is equal to a constant string: MY CONSTANT ST… More on forum.devtalk.com
🌐 forum.devtalk.com
1
July 26, 2022
🌐
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.
🌐
Quora
quora.com › Why-is-null-null-true-in-java
Why is null == null true in java? - Quora
Answer (1 of 8): In java only references can have the value null. As per the Java Language Specification it's "merely a special literal that can be of any reference type". For references == returns true if and only if the value of the two references are the same (or informally "they point to the...
🌐
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.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 523760 › java › null-null-java
null==something vs something==null in java (Beginning Java forum at Coderanch)
If you would have searched you would have found a few earlier topics about this. 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.
🌐
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
🌐
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 ...
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

🌐
Medium
medium.com › @AlexanderObregon › javas-objects-equals-method-explained-3a84c963edfa
Java’s Objects.equals() Method Explained | Medium
5 days ago - The result is cleaner and more maintainable code that eliminates the need for repetitive null checks, allowing developers to focus on the logic rather than on boilerplate code. The Objects.equals() method makes object comparisons in Java easier while handling null values safely.
🌐
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
🌐
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.
🌐
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.
🌐
Devtalk
forum.devtalk.com › backend developer forum › backend questions/help
Java equals() selection - #99999999 - Backend Questions/Help - Devtalk
July 26, 2022 - In Java, if I try to do.equals() on a null string, a null pointer error is issued. I’m wondering whether I can perform the following if I’m attempting to compare if a string is equal to a constant string: MY CONSTANT ST…
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - The null value is not the same as an empty string or an empty array. An empty string is a string that contains no characters, while an empty array is an array that contains no elements. The Java programming language has a built-in null type, called "null", which is a subtype of all reference types.
🌐
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.");
🌐
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.