今天在github上看到了一个开源项目,里面是在整理并翻译stackoverflow上的热门问题,第一个问题是在讨论 i += j 是否等同于 i = i + j;结论是不等于。论证如下:
如果 int i = 9; long j = 11; 那么 i = i + j不能编译,但 i += j 却可以编译。说明i += j,实际是等同于 i= (type of i) (i + j);
参照官方文档:http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2
文档内容:
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);
stackoverflow链接 http://stackoverflow.com/questions/8710619/java-operator
原文git地址为:https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/java-operator.md