Given the following:
Integer var1 = null;
Integer var2 = 4;
Integer result = var1 + var2; // throws NullPointerException
The requirement for my use case is that result
should be null
whenever either operand is null
(and the same applies for other operators). I know I can use an if
statement to do this but is there a smarter way?
Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.
Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.
Some of the most common scenarios for a NullPointerException are: Calling methods on a null object. Accessing a null object's properties. Accessing an index element (like in an array) of a null object.
You can also throw a NullPointerException in Java using the throw keyword.
The best way is not to use Boxed types for normal arithmetic operations. Use primitive types instead.
Only if you are using them in the collections somewhere you should resort to Boxed types.
EDIT:
Incorporating the suggestion from @Ingo there is a good utility class Optional
in Guava, which explains on how to avoid nulls.
Now use of this class makes it explicit that the value can be null
.
Integer var1 = null;
Integer var2 = 4;
Integer result = (var1 == null || var2 == null) ? null : var1 + var2; // returns null if either argument is null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With