String str = "abc";
Comparing this string variable like the following.
if(str.equals("abc")) {}
In case str
is null
, it will cause a java.lang.NullPointerException
to be thrown as obvious.
To avoid that, an additional null check may be enforced. Such as,
if(str != null && str.equals("abc")) {}
I find it plain ugly. Better could be rewritten as follows.
if("abc".equals(str)) {}
This will never throw a java.lang.NullPointerException
even though str
is null
. Besides, object equals null
is never true.
The last case however, cannot be used, when the conditional expression is inverted like so,
if(!"abc".equals(str)) {
System.out.println(str.length());
}
This will cause a java.lang.NullPointerException
inside the if
block, if str
is null
.
Can this somehow be avoided without rewriting the conditional statement like the following?
if(str != null && !"abc".equals(str)) {}
This is plain ugly and unreadable.
Although the example uses a String
object, it may be a more complex object.
An alternative could be to use the Java 8 optional wrapper
source: https://dzone.com/articles/java-8-optional-how-use-it
Long story short : There is simply no library method doing this which I know of. This
if(str != null && !"abc".equals(str)) {}
actually requires that both the objects to be compared are notnull
and not equal to each other.A static utility method performing this task is sufficient to deal with.
You have to check for
null
at some point if you want to usestr
. 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 canstr
benull
and it is possible to prevent it beingnull
by not accepting this value from the very beginning.Another possible way to avoid nulls is using an
assert
: Look at this answer in another similar question:How to check to see that a set of variables is not null before continuing