The following program prints respectively 'false' and 'true':
Number n = true ? new Long(1) : new Double(2.0);
System.out.println(n instanceof Long);
System.out.println(n instanceof Double);
So it will not be a Long but a Double. However, it works as intended on normal classes: Having
class B {}
class D1 extends B {}
class D2 extends B {}
this will print 'true':
B b = true ? new D1() : new D2();
System.out.println(b instanceof D1);
meaning that it is not working the same like the above example.
I'm sure that there is something related to autoboxing, but is it really the way it should work? Why she uses boxing, when the Number class is a superclass of both Long and Double, so that expression could be evaluated to Number?
It's really a pain, because when printing the n, it prints as a double value. (I know it is easy to workaround, but drove me crazy)
?:
takes the type of the last expression. If you made itnull
it would be aLong
:P. – Durante