Copyif (myString != null && !myString.isEmpty()) {
  // doSomething
}

As further comment, you should be aware of this term in the equals contract:

From Object.equals(Object):

For any non-null reference value x, x.equals(null) should return false.

The way to compare with null is to use x == null and x != null.

Moreover, x.field and x.method() throws NullPointerException if x == null.

Answer from polygenelubricants on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - String string1 = "using objects equals"; String string2 = "using objects equals"; String string3 = new String("using objects equals"); assertThat(Objects.equals(string1, string2)).isTrue(); assertThat(Objects.equals(string1, string3)).isTrue(); assertThat(Objects.equals(null, null)).isTrue(); assertThat(Objects.equals(null, string1)).isFalse(); The Apache Commons library contains a utility class called StringUtils for String-related operations; this also has some very beneficial methods for String comparison.
🌐
Pega
support.pega.com › question › what-does-stringutils-equals-method-do-and-how-does-it-work
What does the stringUtils Equals method do and how does it work? | Support Center
May 31, 2018 - this another method to check if this one obj exists or not : ... Compares two Strings, returning true if they are equal. nulls are handled without exceptions. Two null references are considered to be equal.
🌐
Reddit
reddit.com › r/learnjava › best way to check for null on strings?
Best way to check for null on Strings? : r/learnjava
May 8, 2024 - You can use StringUtils.hasText(string) . Will return false if its null
🌐
Apache Commons
commons.apache.org › proper › commons-lang › apidocs › org › apache › commons › lang3 › StringUtils.html
StringUtils (Apache Commons Lang 3.20.0 API)
Operations on String that are null safe. IsEmpty/IsBlank - checks if a String contains text · Trim/Strip - removes leading and trailing whitespace · Equals/Compare - compares two strings in a null-safe manner
🌐
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 - String string = "Hello there"; if (string == null || string.equals("") || string.trim().equals("")) System.out.println("String is null, empty or blank"); else System.out.println("String is neither null, empty nor blank"); In much the same fashion as the before, if the trimmed string is "", it was either empty from the get-go, or was a blank string with 0..n whitespaces: ... The Apache Commons is a popular Java library that provides further functionality. StringUtils is one of the classes that Apache Commons offers.
Find elsewhere
Top answer
1 of 3
2

I feel like the premise of this question is already an incorrect one. You should not have to check for null strings in most places -- in fact, I would argue that you should avoid using null whenever possible, but especially when another non-null sentinel value exists. And String already has a very good "empty" value: the empty string ("")!

If "" and " " need to be folded into the same value, then there's already a perfectly good method for that in the standard library: .trim(). However, .trim(), being an instance method on String, only works on non-null strings. This isn't necessarily a bad thing!

If null and "" mean different things for you, then I would argue that your data model is too complex, and you should be using some other wrapper class rather than using String directly. If null and "" mean the same thing, then you should pick one or the other, and use it consistently. That may mean the need for a few != null checks, but if you find yourself needing an isNullOrEmpty or isNotBlank helper function frequently throughout your codebase, I would say that that's a code smell and you really should work on fixing the underlying data model issues rather than worrying about a tiny helper function.

What does that mean? In the Avoiding != null statements question, the top-voted answer points out that there are really only two kinds of instances where a value can be null: either (1) null is a valid value, or (2) null isn't a valid value.

Case (2) isn't very interesting. Null is not a valid value, so we shouldn't try to deal with it. If anything, we simply throw an exception if we encounter it. Otherwise we ignore it, and let a NullPointerException happen "naturally". It's not supposed to be null, so by definition finding a null is an exceptional situation.

If null is a valid value, then it means null has a semantic meaning. Most likely it means that a value is "not present" or "not valid". There are two sub-cases here: (1a) null means the same thing as the empty string, or (1b) it means something different.

If you have case (1b), then I would argue that you need a new entity in your domain model. For example, you could create a class like PaymentTerm which has separate .isValid() and .isPresent() methods, as well as a .asString() accessor to get the string value if it is present. (The are a lot of possible ways to make a PaymentTerm class, with lots of possible tradeoffs: the point is not that you need this specific form, but that you need something more than a raw String, something that you can hang methods off of, because this thing is now a first-class entity in your domain model.)

If you have case (1a), then null and the empty string both mean the same thing, semantically. But they are very different syntactically! The empty string already has an instance method to check for it (.isEmpty()) and can be safely stored, passed around, compared to other strings, etc.

So case (1a) has two possible solutions: (1a.1) you pass around both null and the empty string, and everywhere you have to check for either, or (1a.2) you normalize nulls to empty strings at the soonest opportunity, and then treat null as an invalid value, and use the empty string everywhere. Depending on your input format, you may even get this behavior "for free" (e.g. an empty text box naturally has the empty string as a value, not null).

My argument is that case (1a.1) is a code smell. Rather than passing around both null and the empty string, and frequently checking for both (either manually or with a method like isNullOrEmpty or isNotBlank), you should try to move into case (2) or case (1a.2).

Note that this answer actually implies that both isNotBlank and != null are sub-optimal! In a well-factored codebase you should strive to avoid both of them, but I tend to think that you should strive to avoid something like isNotBlank even more.

That said, how you check for null or the empty string is not terribly important. The JIT will almost certainly inline the checks anyway, and in many cases the peephole optimizer will elide them completely if it can prove null-safety another way. The far more important thing to consider is whether null is a valid value in your program, and if so, what it means semantically for a value to be null.

2 of 3
1

paymentTerm != null and StringUtils.isNotBlank(paymentTerm) don't perform the same thing.
If you want to only check the non nullity of a String object, you don't want to use isNotBlank() but use != null. So it may still make sense to use != null.
Note that as alternative you could also use Object.nonNull(Object) but it is often more verbose (but in a method reference where it makes completely sense : Object::nonNull).

After about whether we should test != "", != trimmed "" or just != null, it is a requirement matter.
Even if isNotBlank() includes != null, you will use it only as it is required because performing more checks that required is misleading code.


Here are simple examples where you can see that each way has a meaning and you have to use them (or no of them) in a way what makes their reading natural and pleasant.

1) You want to check the String length size.

if (myString != null && myString.length() == 8)

is what you need.
Doing it with isNotBlank() is verbose and conveys two very specific things (not blank and min length) while only the last one matters.

if (StringUtils.isNotBlank(myString) && myString.length() == 8)

2) You want to check that the String contain some characters.

if (myString != null && myString.contains("word"))

is still what you need.

if (String.isNotBlank(myString) && myString.contains("word"))  

Doing it with isNotBlank() appears still as noise.

3) You want to check the String equal to another one that cannot be null or that is a compile-time constant expression.

You want to directly write :

if ("word".equals(myString))

4) So when do you want to use isNotBlank() ?
Only when you need to check that a String is not null and doesn't contain only whitespaces (" ") characters.

if (StringUtils.isNotBlank("word"))
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.1 › index.html
StringUtils (Commons Lang 3.1 API)
Commons Lang 3.1 API · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link toNon-frame version
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-2.6 › org › apache › commons › lang › StringUtils.html
StringUtils (Commons Lang 2.6 API)
StringUtils.stripAll(null, *) = ... "yz") = ["abc ", null] StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null] ... Compares two Strings, returning true if they are equal....
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:

String 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:

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

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

String 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:

String 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.

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

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

boolean 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
s == null

won't work?

🌐
Medium
medium.com › @bectorhimanshu › avoiding-nullpointerexception-using-null-safe-libraries-in-java-81cb414a978d
Avoiding NullPointerException using null-safe libraries in Java | by bectorhimanshu | Medium
September 29, 2023 - Lets try to understand with the help of different examples that how we can use StringUtils to handle potential null Strings and avoid ‘NullPointerException’: ... public class TestDemo { public static void main(String[] args) { String str1 = null; String str2 = “”; String str3 = “Himanshu, Bector!”; // Check for null or empty string System.out.println(“Is str1 null or empty: “ + StringUtils.isEmpty(str1)); // true
🌐
Medium
alaya-hamza1.medium.com › professional-java-d202afd88629
Java Strings for you!. How to Compare Strings in Java ?! | by Alaya Hamza | Medium
March 12, 2021 - This method is used to sort a list of strings with null entries. assertThat(StringUtils.compare(null, null)) .isEqualTo(0); assertThat(StringUtils.compare(null, "abc")) .isEqualTo(-1); assertThat(StringUtils.compare("abc", "bbc")) .isEqualTo(-1); ...
🌐
GitHub
github.com › aws › aws-sdk-java-v2 › issues › 6603
StringUtils.equals returns false if both arguments are null · Issue #6603 · aws/aws-sdk-java-v2
October 21, 2025 - Describe the bug StringUtils.equals' javadoc says that passing in two nulls will return true, but the code will always return false because it does a short circuit check for if one of them is null. Changing it to return true would match ...
Published   Dec 02, 2025