Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid NullPointerException from arithmetic operators 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?

like image 879
Steve Chambers Avatar asked Nov 21 '13 09:11

Steve Chambers


People also ask

How do you stop NullPointerException in Java?

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.

What can help us in avoiding NullPointerException and null checks in Java?

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.

Which of the following options can throw a NullPointerException?

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.

Can we throw NullPointerException in Java?

You can also throw a NullPointerException in Java using the throw keyword.


2 Answers

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.

like image 52
Narendra Pathai Avatar answered Sep 19 '22 02:09

Narendra Pathai


Integer var1 = null;
Integer var2 = 4;
Integer result = (var1 == null || var2 == null) ? null : var1 + var2; // returns null if either argument is null
like image 25
stackular Avatar answered Sep 19 '22 02:09

stackular