直接上代码解释
/** * 面试题: * short s = 1; * s = s + 1; * * short s = 1; * s += 1; * * 上面两个代码有么有问题,如果有,哪里有问题? * @author wangjg * */ public class OperatorTest { public static void main(String[] args) { /** * Type mismatch: cannot convert from int to short * 会在编译时报错误,s为short类型,在参与运算的时候,s会自动提升类型为int,int和int相加结果为int * 再赋值给short,会丢失精度 */ // short s = 1; // s = s + 1; // System.out.println(s); /** * +=就不会报错,因为+=会自动带上强制转换,可以查看下class反编译文件 * s += 1; * 相当于 * s = (short)(s + 1); */ short s = 1; s += 1; System.out.println(s); } }