今天在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);
對複合賦值運算式來說,E1 op= E2 (諸如 i += j; i -= j 等等),其實是等同於 E1 = (T)((E1) op (E2)),其中,T是E1這個元素的類型。
stackoverflow連結 http://stackoverflow.com/questions/8710619/java-operator
原文git地址為:https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/java-operator.md
A c