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")); }
🌐
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.
🌐
CodeQL
codeql.github.com › codeql-query-help › csharp › cs-null-argument-to-equals
Null argument to Equals(object) — CodeQL query help documentation
If the object really is null, a NullReferenceException is thrown when attempting to call Equals, with unexpected results.
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?

🌐
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.
Find elsewhere
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 117372-check-if-string-null.html
Check if string is null
Can you tell me how to check if a string is null in C? I tried p != '\0' doent seem to wrk though! It all depends on what you mean, and what p is declared as. That looks like an empty string check to me.
🌐
LabEx
labex.io › tutorials › c-how-to-ensure-string-null-termination-438491
How to ensure string null termination | LabEx
Explore essential C programming techniques for safe string null termination, preventing buffer overflows and memory-related errors in string handling.
🌐
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)
If I were checking for a particular constant, I could just do "Joe".equals(name). But either argument could be null in my case. Any ideas would be appreciated, Thanks, Jason. ... Why don't you check if any of the values/variables are false? If any is then don't do the comparison. If none of them is null, use the eqauls() method to do your comparison. Good luck, Bosun · Bosun (SCJP, SCWCD). So much trouble in the world -- Bob Marley ... The way to compare String object contents is to use the equals() method.
🌐
Runebook.dev
runebook.dev › en › docs › c › string › byte
From Null to Now: A Beginner's Guide to C Strings
Solution Always allocate one extra byte for the null terminator. ... Even better, use a string literal to initialize it. The compiler automatically adds the \0 for you. ... This is the most common and safest way to declare a string in C.
🌐
C For Dummies
c-for-dummies.com › blog
Null Versus Empty Strings | C For Dummies Blog
A null string has no values. It’s an empty char array, one that hasn’t been assigned any elements. The string exists in memory, so it’s not a NULL pointer.
🌐
TutorialsPoint
tutorialspoint.com › comparing-strings-with-possible-null-values-in-java
Comparing Strings with (possible) null values in java?
Enter your first string value: ... apple preceeds mango · 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....
🌐
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 ·
🌐
Runebook.dev
runebook.dev › en › docs › c › string › byte › strlen
strlen in C: A Guide to Safe String Handling
This is probably the most common mistake. If a string isn't properly null-terminated, strlen won't know where to stop counting.