题目:
short s = 1; s = s + 1;
short s = 1; s += 1;
上面两组代码有没有问题,如果有,哪里出现了问题?
class Demo {
public static void main(String args[]){
//short s = 1;
//s = s + 1;
//System.out.println(s);
short s = 1;
s += 1;
System.out.println(s);
}
}
第一组代码中short参加运算需要向上转型转成int
这样会损失精度
第二组代码没有问题,因为扩展的赋值运算符隐含了一个强制类型转换。
s += 1;
不等价于s = s + 1;
而是等价于 s = (s的数据类型) (s + 1);