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
🌐
Blogger
marxsoftware.blogspot.com › 2021 › 02 › java-nullpointerexception-avoidance-and.html
Inspired by Actual Events: Java NullPointerException Avoidance and Enhancement Tactics
The tactic of calling .equals(Object) against the known non-null object is demonstrated in the next code listing and associated output. /** * Demonstrates that comparisons against known non-{@code null} strings can be * {@code null}-safe as long as the known non-{@code null} string is on the left * side of the {@link Object#equals(Object)} method ({@link Object#equals(Object)}) * is called on the known non-{@code null} string rather than on the unknown * and potential {@code null}. */ public void demonstrateLiteralComparisons() { executeOperation( "Using known non-null literal on left side of .equals", () -> "Inspired by Actual Events".equals(NULL_STRING)); executeOperation( "Using potential null variable on left side of .equals can result in NullPointerExeption", () -> NULL_STRING.equals("Inspired by Actual Events")); }
🌐
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.
🌐
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.
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - The method returns true if two Strings are equal by first comparing them using their address i.e “==”. Consequently, if both arguments are null, it returns true and if exactly one argument is null, it returns false.
🌐
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.
Find elsewhere
🌐
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 to the case of the characters in the strings ...
🌐
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 ·
🌐
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.
🌐
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....
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.string.equals
String.Equals Method (System) | Microsoft Learn
The second string to compare, or null. ... true if the value of a is the same as the value of b; otherwise, false. If both a and b are null, the method returns true. The following example demonstrates the Equals method.
🌐
Coderanch
coderanch.com › t › 387952 › java › avoid-null-pitfalls-comparing-Strings
How do I avoid null pitfalls when comparing Strings? (Beginning Java forum at Coderanch)
For this type of thing I switched it around and did it like "MyValue".equals(myVar), which won't throw an exception if myVar is null. I know that doesn't completely address your particular issue. For your problem, you might want to consider writing a function to handle your comparison, particularly if you do this often in your code. You could go with the try/catch or a couple of if/then statements to check for null before doing the comparison inside the function. ... Assuming your String reference variables are strObj1 and strObj2, you could do the following: -Peter
🌐
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 - Note: It's important to do the null-check first, since the short-circuit OR operator || will break immediately on the first true condition. If the string, in fact, is null, all other conditions before it will throw a NullPointerException.
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?

🌐
W3Docs
w3docs.com › java
How to check if my string is equal to null?
String str = null; if (str.equals(null)) { // This will throw a NullPointerException // The string is null }
🌐
How to do in Java
howtodoinjava.com › home › string › java string.equals()
Java String.equals() with Examples - HowToDoInJava
January 9, 2023 - The String.equals() in Java compares a string with the object passed as the method argument. It returns true if and only if: the argument object is of type String · the argument object is not null · represents the same sequence of characters as the current string ·
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › class
Null safe equals method - Java Code Geeks
July 21, 2013 - */ public static boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.equals((Object[]) o1, (Object[]) o2); } if (o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[]) o1, (boolean[]) o2); } if (o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[]) o1, (byte[]) o2); } if (o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[]) o1, (char[])