A simple expression:
Object val = true ? 1l : 0.5;
What type is val? Well, logically, val should be a Long object with value 1. But Java thinks that val is a Double with value 1.0.
It doesn’t have to to anything with autoboxing as
Object val = true ? new Long(1) : new Double(0.5);
results with same behavior.
Just to clarify:
Object val = true ? "1" : 0.5;
results in the correct String.
Can anybody explain me why they have defined this like that? For me it seems to be rather really bad designed or actually a bug.
This is described in the Java Language Specification Section 15.25 (relevant parts in bold face):
The “lub” mentioned in the last paragraph stands for least upper bound and refers to the most specific super type common for T1 and T2.
As for the case with
Object val = true ? 1l : 0.5;I agree that it would be more precise if it applied rule 5 (on the boxed values). I guess the rules would become ambiguous (or even more complicated) when taking autoboxing into account. What type would for instance the expressionb ? new Byte(0) : 0.5have?You can however force it to use rule 5 by doing