Unfortunately no, there is no other way in Java to prevent NullPointerException
on boxed types other than to explicitly check for null
.
The same applies to .equals()
, you can do:
Integer var1 = null;
Integer var2 = 4;
var1 == var2
But if you want to compare values:
Integer var1 = null;
Integer var2 = 4;
var1.equals(var2) //throws NullPointerException
This is why a two argument static Object::equals
(see here) was introduced in 2011 to Java.
There are no such methods for boxed numbers (like Integer
). In fact during var1 + var2
you get automatic unboxing which causes exception. So you are not adding two Integer
s, but .intValue()
is called instead on both of them, and then a new Integer is constructed from the result.
See this Stack Overflow answer for further information on boxed numbers: Unboxing Long in java.
Sorry, this is one of the Java's nuisance. If you work on Integer
s, check for null
every time.