no compiler error when assigning null to a primitive with ? :

In 5.0, the statement

int a = true ? null : 0;

does not produce a compiler error. In 1.4 it produced an error stating "Incompatible conditional operand types int and null". I understand that auto-boxing complicates the compiler's job here, but isn't it still possible for the compiler to error on this statement?

[334 byte] By [Brian.Edwardsa] at [2007-10-2 20:21:53]
# 1
You know, one thing I never found out was whether they decided to go with null autoboxing to 0 or making that an error. What happens when you run it?
dubwaia at 2007-7-13 23:04:28 > top of Java-index,Core,Core APIs...
# 2

That's perfectly legit in 1.5 because of autoboxing.

The compiler looks at the expression

true?null:0

and needs to determine the type produced by it. 0 can be autoboxed to an Integer and null is a valid Integer value, so that expression produces an Integer.

Then, it tries to auto-unbox the Integer to assign it to the primitive int. And the same thing happens as always happens when you try to auto-unbox null: you get a NullPointerException. :)

tvynra at 2007-7-13 23:04:28 > top of Java-index,Core,Core APIs...
# 3

thanks for the response. considering that the compiler evaluates the expression to an Integer and then autoboxes, I can't understand why the following statement DOES generate a compiler error:

int y = true ? null : null;

It generates "Type mismatch: cannot convert from null to int". Why doesn't the compiler catch this in the previous case?

Brian.Edwardsa at 2007-7-13 23:04:28 > top of Java-index,Core,Core APIs...
# 4

It has to do with how the type of an ternary expression is evaluated. One thing that is obvious is that because there null has no type, nothing can be detemined from two nulls where having one int can provide a type. The JLS explains this in detail. If you really care that much, you can look there.

dubwaia at 2007-7-13 23:04:28 > top of Java-index,Core,Core APIs...