2009-03-03 327 views

回答

23

INT = INT +雙基本上是

INT =雙+雙

,你不能做,沒有鑄造...

的int + =雙重力量的結果爲int而另一個需要鑄造。

所以a =(int)(a + b);

應該編譯。

編輯:按照意見要求...這裏是更多的閱讀鏈接(不是最容易讀,但最正確的信息):http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

+0

你能否提供一些鏈接,以便進一步閱讀?謝謝 – hhafez 2009-03-04 00:32:30

+0

我認爲「深層次」的原因是因爲它不允許在縮小時進行賦值:byte = int是不允許的,int也是double。會做一個簡單的字節a; a + = 2;並且不能編譯,人們會在java上扔鞋子。但我仍然會喜歡額外的規則,使其工作沒有演員:( – 2009-03-04 01:20:45

32

在Java + =運營商有一個隱式轉換到左手型。這適用於所有組合的操作員。

4

雙+ INT返回雙,所以 雙=雙+ int是合法的,見JLS 5.1.2另一方面寬元轉換 INT =雙+ INT是「基本收縮轉換」,需要明確的投

0

正如每個人都已經說過的那樣,+ =有一個隱含的強制轉換。爲了說明這一點,我將使用一個我後來寫的應用程序,這對於這些類型的問題來說是完美的。這是一個在線的反彙編,以便您可以檢查出真實而產生的實際字節碼:http://javabytes.herokuapp.com/

及其含義的表: http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings

那麼讓我們來看看一些簡單的Java代碼的字節碼:

int i = 5; 
long j = 8; 
i += j; 

反彙編代碼。我的評論將有一個//在前面。

Code: 
     0: iconst_5 //load int 5 onto stack 
     1: istore_0 //store int value into variable 0 (we called it i) 
     2: ldc2_w #2; //long 8l 
        //load long 8 value onto stack. Note the long 8l above 
        //is not my comment but how the disassembled code displays 
        //the value long 8 being used with the ldc2_w instruction 
     5: lstore_1 //store long value into variable 1 (we called it j) 
     6: iload_0 //load int value from variable 0 
     7: i2l  //convert int into a long. At this point we have 5 long 
     8: lload_1 //load value from variable 1 
     9: ladd  //add the two values together. We are adding two longs 
        //so it's no problem 
     10: l2i  //THIS IS THE MAGIC. This converts the sum back to an int 
     11: istore_0 //store in variable 0 (we called it i)