Java Reference
In-Depth Information
The conditional operator expression has a type that is determined by the
types of the second and third expressions ( usersValue and defaultValue
in the above example). If the types of these expressions are the same
then that is the type of the overall expression. Otherwise, the rules get
somewhat complicated:
If one expression is a primitive type and the other can be un-
boxed to become a compatible primitive type, then the unboxing
occurs and the expressions are reconsidered.
If both expressions are numeric primitive types then the resulting
type is also a numeric primitive type, obtained by numeric pro-
motion if needed. For example, in
double scale = (halveIt ? 0.5 : 1);
the two expressions are of type double ( 0.5 ) and type int ( 1 ). An
int is assignable to a double , so the 1 is promoted to 1.0 and the
type of the conditional operator is double .
If one expression is an int constant, and the other is byte , short ,
or char , and the int value can fit in the smaller type, then the res-
ulting type is that smaller type.
If one of the expressions is a primitive type and the other is a ref-
erence type that can't be unboxed to get a compatible value, or
both expressions are primitive but incompatible, then the primit-
ive type is boxed so that we have two reference types.
Given two reference types that are different, the type of the ex-
pression is the first common parent type. For example, if both ex-
pressions were unrelated class types that implemented Cloneable
then Cloneable would be the type of the expression; if one expres-
sion was int while the other was String , then Object would be the
resulting type.
Note that if either expression has a type of void (possible if the expres-
sion invokes a method with the void return type) then a compile-time
error occurs.
 
Search WWH ::




Custom Search