java 中的 shorthand 运算符与普通运算符有何不同?
how does shorthand operator in java works different from normal operator?
我知道默认情况下数字在 java 中存储为整数,但是
byte x = 10;
x = x + 10;
在
时出错
byte x = 10;
x += 10;
编译正常
JLS有一个答案给你
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.
short x = 3;
x += 4.6;
并导致 x 的值为 7,因为它等同于:
short x = 3;
x = (short)(x + 4.6);
所以在你的情况下你的第二个陈述等于
x = (byte) x + 10;
这就是编译器高兴的原因。
我知道默认情况下数字在 java 中存储为整数,但是
byte x = 10;
x = x + 10;
在
时出错byte x = 10;
x += 10;
编译正常
JLS有一个答案给你
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.
short x = 3;
x += 4.6;
并导致 x 的值为 7,因为它等同于:
short x = 3;
x = (short)(x + 4.6);
所以在你的情况下你的第二个陈述等于
x = (byte) x + 10;
这就是编译器高兴的原因。