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)shouldreturn 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.
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)shouldreturn 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.
If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.
Check for null first like this:
Copyif (myString != null && !myString.equals("")) {
//do something
}
This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.
When I type
string1 == string2
IntelliJ tells me to switch to equals(), which it says is null-safe.
But is == operator not null-safe?
I tried null == "abc", "abc" == null, null == null, but they consistently gave me right false false true.
What am I missing here?
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.
This is what Java internal code uses (on other compare methods):
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
StringUtils.isBlank() checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.
From the linked documentation:
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false
For comparison StringUtils.isEmpty:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true for null.
java.lang.String.isBlank() (since Java 11)
java.lang.String.isEmpty()
The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,
StringUtils.isBlank()
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
StringUtils.isEmpty
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
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.
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"))
You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.
It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).
Use Objects.equals() to compare strings, or any other objects if you're using JDK 7 or later. It will handle nulls without throwing exceptions. See more here: how-do-i-compare-strings-in-java
And if you're not running JDK 7 or later you can copy the equals method from Objects like this:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
What about isEmpty() ?
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.
To ignore whitespace as well:
if(str != null && !str.trim().isEmpty())
(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)
Wrapped in a handy function:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
Becomes:
if( !empty( str ) )
Use org.apache.commons.lang.StringUtils
I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
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.
s == null
won't work?
If Java 7+, use Objects.equals(); its documentation explicitly specifies that:
[...] if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
which is what you want.
If you don't, your method can be rewritten to:
Copyreturn s1 == null ? s2 == null : s1.equals(s2);
This works because the .equals() contract guarantees that for any object o, o.equals(null) is always false.
From Objects.equals():
Copyreturn (a == b) || (a != null && a.equals(b));
Very simple, self-explaining and elegant.
An alternative could be to use the Java 8 optional wrapper
Optional<Customer> optional = findCustomer();
if (optional.isPresent()) {
Customer customer = maybeCustomer.get();
... use customer ...
}
else {
... deal with absence case ...
}
source: https://dzone.com/articles/java-8-optional-how-use-it
You have to check for null at some point if you want to use str. There is simply no way around it. You can wrap this check into a additional utility function or something like this, but in the end you will not get around the additional check.
If you are a friend of using loads of additional libraries you could use org.apache.commons.lang.StringUtils#length(java.lang.String). That does just what you want, maybe you got a library like that present in your application anyway. The apache one is only a example. There are surely others around that do similar things.
If you want to remove the null check all together maybe the better question is: Why can str be null and it is possible to prevent it being null by not accepting this value from the very beginning.