'A utility method representing, "Both not null and not equal" in Java
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.
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CarefreeCrayon |
| Solution 2 | Nitram |
| Solution 3 | Community |
