2

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.
Community
  • 1
  • 1
yfklon
  • 148
  • 1
  • 13
  • 1
    You mean, it was a wrong design decision? You probably would have liked to see a coercion to the _expected_ result type of `b2`. That would introduce a far more complex parsing, like in `A ? (a ? b : c) : D`. But that is partially done for generics and lambda expressions. Be happy for simple rules. โ€“ Joop Eggen Jul 01 '15 at 16:58
  • @JoopEggen Actually I didn't mean that it was a wrong design decision, asked to learn the reason of it. If you have an answer, could you explain it? โ€“ yfklon Jul 01 '15 at 17:11
  • Oh, in that case: a primitive type value is more operational than the corresponding wrapper object, hence for balancing two then-else types one would pick the primitive type as target (motivation for the rule cited above). Java simply did not start as a pure OO language but retained primitive non-Object types. โ€“ Joop Eggen Jul 02 '15 at 06:04

1 Answers1

2

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.

biziclop
  • 48,926
  • 12
  • 77
  • 104