Steve Chambers Steve Chambers - 23 days ago 18
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


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

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.

Comments