public class MyTest { public static void main(String args[]){ short s1=32767; s1+=1; int i=32768; short s2=(short)i; System.out.println(s1); System.out.println(s2); } }
这是规范的原文A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T )((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. For example, the following code is correct: short x = 3; x += 4.6; and results in x having the value 7 because it is equivalent to: short x = 3; x = (short)(x + 4.6);
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T )((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. For example, the following code is correct: short x = 3; x += 4.6; and results in x having the value 7 because it is equivalent to: short x = 3; x = (short)(x + 4.6);
(T)((E1)op(E2)),其中T 是E1 的类型,除非E1 只被计算一次。
换句话说,复合赋值表达式自动地将它们所执行的计算的结果转型为其左侧变量
的类型。
public static void main(String args[]){
short s1=32767;
s1+=1;
int i=32768;
short s2=(short)i;
System.out.println(s1);
System.out.println(s2);
}
}
E1 = (T )((E1) op (E2)), where T is the type of E1, except that E1 is evaluated
only once.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
x+=1 就是 x=x+1
无论谁怎么调用这个+=
都是调用等号左边的那个自己的值再加上右边的那个值,再回来赋值给它自己.
s1=s1+1; //s1+1的结果是int型,把int型赋值给short型会报错
s1+=1; //为什么s1+=1是正确的?回答:
s1 += 1 相当 s1 = (short)(s1+1),即默认加了强制类型转换,所以正确
实际上无论使用,还是国际编码规范中,都推荐使用s1=s1+1
一个为了清晰,另一个就是s1=s1+1如果类型不对会报错,可以帮助调整代码中变量的类型。
所以变量类型的定义非常重要。