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 › @thilinajayawardana_85346 › java-string-nullpointerexception-safe-equals-check-404481934e9b
Java String NullPointerException safe equals check | by Thilina Jayawardana | Medium
June 30, 2020 - Java String NullPointerException safe equals check If you compare two Strings in Java, normally you would use the equals method to compare them to see if they are similar. This will be some common …
🌐
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:
🌐
Blogger
marxsoftware.blogspot.com › 2021 › 02 › java-nullpointerexception-avoidance-and.html
Inspired by Actual Events: Java NullPointerException Avoidance and Enhancement Tactics
Although it was specifically String.equals(Object) demonstrated above, this tactic applies to instances of any class as long as the class's .equals(Object) method can gracefully handle a supplied null (and I cannot recall ever encountering one that didn't handle null). Case Insensitive Comparison of Strings Safely with Known Non-null String on LHS of .equals(Object)
🌐
Blogger
tjisblogging.blogspot.com › 2020 › 06 › java-string-nullpointerexception-safe.html
Java String NullPointerException safe equals check
Thus a NullPointerException. The better way to do it will be like follows. 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.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › equals
Java String equals() - Compare Strings Equality
December 23, 2024 - Consequently, the equals() method returns false. Understand that invoking equals() on a null reference will throw a NullPointerException. Perform a null check before using equals() for comparison.
Find elsewhere
🌐
Attacomsian
attacomsian.com › blog › ways-to-compare-strings-in-java
4 ways to compare strings in Java
February 18, 2020 - That's folks for comparing strings in Java. We discussed 4 different ways to compare two strings with each other. You should always use Objects.equals() as it is null-safe and performs better.
🌐
Medium
medium.com › @AlexanderObregon › javas-objects-equals-method-explained-3a84c963edfa
Java’s Objects.equals() Method Explained | Medium
5 days ago - This approach is null-safe, making sure that the method works correctly even if the key or value being searched for is null. In many cases, Objects.equals() helps clean up conditional logic that involves null checks and comparisons.
🌐
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 ...
🌐
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 ...
🌐
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
Top answer
1 of 16
187

string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.


Longer answer:

If you try this, it won't work, as you've found:

CopyString foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.

What you probably wanted was:

CopyString foo = null;
if (foo == null) {
    // That will work.
}

The typical way to guard yourself against a null when dealing with Strings is:

CopyString foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.

The easy way, if you're using a String literal (instead of a variable), is:

CopyString foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.

Copyif (StringUtils.equals(foo, bar)) {
    // Do something here.
}

Another response was joking, and said you should do this:

Copyboolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

2 of 16
33
Copys == null

won't work?

🌐
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....
🌐
TechVidvan
techvidvan.com › tutorials › java-string-equals-method
Java String equals() Method - TechVidvan
March 18, 2024 - String Literal : It can be applied ... 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....
🌐
Stack Abuse
stackabuse.com › java-check-if-string-is-null-empty-or-blank
Java: Check if String is Null, Empty or Blank
February 28, 2023 - One of the key differences between StingUtils and String methods is that all methods from the StringUtils class are null-safe.