Skip to content
Advertisement

A utility method representing, “Both not null and not equal” in Java

JavaScript

Comparing this string variable like the following.

JavaScript

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,

JavaScript

I find it plain ugly. Better could be rewritten as follows.

JavaScript

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,

JavaScript

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?

JavaScript

This is plain ugly and unreadable.


Although the example uses a String object, it may be a more complex object.

Advertisement

Answer

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 not null and not equal to each other.

A static utility method performing this task is sufficient to deal with.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement