Skip to content
Advertisement

How to avoid NullPointerExceptions from boxed type arithmetic in Java?

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?

Advertisement

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.

Advertisement