Monday, 22 December 2014

The Terrible Dangers of Autoboxing (Part 3) - Solution

The solution to my previous post regarding the Terrible Dangers of Autoboxing, is written below.

In our case, the type of the second expression is 0L (long) and the third is null but returns from a Long method.

Java assumes that the second and third operands have types that are convertible to numeric types.

In that case, the conditional operator causes binary numeric promotion.2

During binary numeric promotion, it is possible an unboxing is performed3 (on null in our case), which consequently fails with a NullPointerException.

The solution is to replace
return hasSurfaceArea() && getSurfaceInM2() == null ? 0L : getSurfaceInM2();
With:
return hasSurfaceArea() && getSurfaceInM2() == null ? Long.valueOf(0) : getSurfaceInM2();

P.S. Rewriting the conditional expression into an if statement, will also solve it.

Quote

Here is a brilliant quote that every Java programmer needs to remember and understand (especially that last bit):
“Autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.1

References

[1] Java SE Documentation - Autoboxing
http://docs.oracle.com/javase/7/docs/technotes/guides/language/autoboxing.html
[2] Chapter 15.25 Conditional Operator ? :
Java Language Specification
[3] Chapter 5.6.2 Binary Numeric Promotion
Java Language Specification
Java Tutorials - Autoboxing and Unboxing
http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

No comments:

Post a Comment