判断下列代码是否正确
题目:
short s1 = 1; s1 = s1 + 1; 有错吗?
short s2 = 1; s2 += 1 有错吗?
为什么?
一、测试
- 原代码演示:
package com.learn.interview;
/**
* short s1 = 1; s1 = s1 + 1; 有错吗?
* short s2 = 1; s2 += 1 有错吗?
*/
public class interview_02 {
public static void main(String[] args) {
short s1 = 1;
s1 = s1 + 1; // java: 不兼容的类型: 从int转换到short可能会有损失
System.out.println(s1);
short s2 = 1;
s2 += 1;
System.out.println(s2);
}
}
- 运行结果:
build failed
interview_02.java
不兼容的类型: 从int转换到short可能会有损失 10
- 改变代码演示:
package com.learn.interview;
/**
* short s1 = 1; s1 = s1 + 1; 有错吗?
* short s2 = 1; s2 += 1 有错吗?
*/
public class interview_02 {
public static void main(String[] args) {
short s1 = 1;
s1 = (short) (s1 + 1);
System.out.println("s1的结果为:" + s1);
short s2 = 1;
s2 += 1;
System.out.println("s2的结果为:" + s2);
}
}
- 运行结果:
s1的结果为:2
s2的结果为:2
Process finished with exit code 0
二、结论
short s1 = 1; s1 = s1 + 1;不正确,short s2 = 1; s2 += 1;正确。
对于 short s1 = 1; s1 = s1 + 1;
由于1是 int 类型,因此 s1+1 运算结果也是 int 型,需要强制转换类型才能赋值给 short 型。
而short s2 = 1; s2 += 1;
可以正确编译,因为 s1+= 1;相当于 s1 = (short)(s1 + 1);其中有隐含的强制类型转换。