关键lz想要的就是类型转换问题,比如, int i = 0; i += 1; i += 'a'; i += 1.2d; i += 353534444345345345L; i += 3.2f; byte b = 7; i += b; i += (byte) 7; i += (char) 65; 等牛人解释。。
不需要理解的太复杂吧?基本上就是自动帮你加个强转而已。比如: i += expRight; 约等于 i = (int) (i + expRight);
这个说法不对。不是先把1.2d转化为int再去计算;而是先把右边按常规情况计算完毕,再进行强转,而且这个计算过程,等式左边的变量是直接参与的。比如: int i = 2; i *= 1.6d; 结果 i == 3其实就是: int i = 2; i = (int) (i * 1.6d); // 计算过程中,会先升级为double进行运算,得到3.2,最后才强转为3。
from:java language specification15.26.2 Compound Assignment Operators 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);
int i = 0;
i += 1;
i += 'a';
i += 1.2d;
i += 353534444345345345L;
i += 3.2f;
byte b = 7;
i += b;
i += (byte) 7;
i += (char) 65;
等牛人解释。。
i += expRight;
约等于
i = (int) (i + expRight);
i+=1.2d以及以下的。
首先将该表达式转化以下i=i+1.2d;
就是将1.2d转化成int在与int i相加。
所以结果是int类型的
这个说法不对。不是先把1.2d转化为int再去计算;而是先把右边按常规情况计算完毕,再进行强转,而且这个计算过程,等式左边的变量是直接参与的。比如:
int i = 2;
i *= 1.6d;
结果 i == 3其实就是:
int i = 2;
i = (int) (i * 1.6d);
// 计算过程中,会先升级为double进行运算,得到3.2,最后才强转为3。
from:java language specification15.26.2 Compound Assignment Operators
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);