Search code examples
javajvmjavac

Why wrapped type unboxed instead of boxing the primitive?


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.

Solution

  • Consider this scenario:

     Boolean b1 = new Boolean(false); //I know you shouldn't be doing this but it's valid
     boolean foo = b1 == false;
     Boolean bar = b1 == false;
    

    Now if things worked like you probably expect them to be, foo would be true and bar would be false. Or, alternatively both could be false but that would mean autoboxing everything all the time if just a single boxed primitive occurs in the expression. (And then potentially unboxing it for the assignment.)

    I wouldn't consider that a good trade-off. Granted, dealing with NPEs from unboxing conversions is ugly but it's something you have to do anyway in most unboxing scenarios.