Java += 操作符實質__Java

來源:互聯網
上載者:User

今天在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.