3 回答
TA贡献1854条经验 获得超8个赞
条件运算符中的数值转换?:
在条件运算符中,如果和都是不同的数字类型,则在编译时将应用以下转换规则,以使它们的类型相等,顺序是:a?b:cbc
这些类型将转换为它们对应的原始类型,这称为unboxing。
如果一个操作数是一个常量
int(不在Integer拆箱之前),其值可以用另一种类型表示,则该int操作数将转换为另一种类型。否则,较小的类型将转换为下一个较大的类型,直到两个操作数具有相同的类型。转换顺序为:
byte->short->int->long->float->doublechar->int->long->float->double
最终,整个条件表达式将获得其第二和第三操作数的类型。
示例:
如果char与组合short,则表达式变为int。
如果Integer与组合Integer,则表达式变为Integer。
如果final int i = 5与a 组合Character,则表达式变为char。
如果short与组合float,则表达式变为float。
在问题的例子,200从转换Integer成double,0.0是装箱从Double进入double和整个条件表达式变为变为double其最终盒装入Double因为obj是类型Object。
TA贡献1884条经验 获得超4个赞
例:
public static void main(String[] args) {
int i = 10;
int i2 = 10;
long l = 100;
byte b = 10;
char c = 'A';
Long result;
// combine int with int result is int compiler error
// result = true ? i : i2; // combine int with int, the expression becomes int
//result = true ? b : c; // combine byte with char, the expression becomes int
//combine int with long result will be long
result = true ? l : i; // success - > combine long with int, the expression becomes long
result = true ? i : l; // success - > combine int with long, the expression becomes long
result = true ? b : l; // success - > combine byte with long, the expression becomes long
result = true ? c : l; // success - > char long with long, the expression becomes long
Integer intResult;
intResult = true ? b : c; // combine char with byte, the expression becomes int.
// intResult = true ? l : c; // fail combine long with char, the expression becomes long.
}
添加回答
举报
