I've read the following question Booleans, conditional operators and autoboxing. I am wondering why wrapped types unboxed to primitives instead of boxing the primitives to wrappers. Is this just a performance optimization?
Details
The type of conditional expression below is boolean. And there is a hidden NPE.
Third operand (b1
) of the expression unboxed (throws NPE) and immediately reboxed (if there is no exception).
Boolean b1 = null;
Boolean b2 = null != b1 ? false : b1;
Instead of this, second operand (primitive false value) can be boxed to Boolean.FALSE. The question is, why the first way is preferred?
Explanations about the type of conditional expressions here.
- If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion
(ยง5.1.7) to T, then the type of the conditional expression is T.