NPE while AutoBoxing
-
Auto-boxing and Unboxing is a feature of Java which allows us to assign primitives to wrappers and vice versa. But, at times while boxing there could be a chance of
NPE
ifnull
checks are not done. -
Auto-boxing:
-
Double price = 10.5; // primitve -> wrapper
-
-
Unboxing:
-
Double price = new Double(10.5); double price1 = price; // wrapper -> primitive
-
Direct assignment of
null
to primitives is not allowed in Java-
double price = null; // Doesn't compile
-
-
However, a
null
value of wrapper type can be assigned to a primitive type, which would causeNPE
.-
Double price = null; // Assume this value is passed in from caller double localPrice = price; // compiles but results in NPE /*- Error: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Double.doubleValue()" because "price" is null */
-
Conisder the following snippet
private static void computePrice(double price) { // operation involving price } // caller Double d = null; // assume we got null by calling another service or function computePrice(d); // compiles, but throws NPE
-
-
-
In sum, it’s always good to do null checks in the code, and have a dedicated unit test case
when_null_value_is_passed_in_to_<method-name>