Steve Chambers Steve Chambers - 5 months ago 51
Java Question

How to avoid NullPointerException from arithmetic operators in Java?

Given the following:

Integer var1 = null;
Integer var2 = 4;
Integer result = var1 + var2; // throws NullPointerException

should be
whenever either operand is
(and the same applies for other operators). I know I can use an
statement to do this but is there a smarter way?


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.


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.