正如每個人都已經說過的那樣,+ =有一個隱含的強制轉換。爲了說明這一點,我將使用一個我後來寫的應用程序,這對於這些類型的問題來說是完美的。這是一個在線的反彙編,以便您可以檢查出真實而產生的實際字節碼: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)
你能否提供一些鏈接,以便進一步閱讀?謝謝 – hhafez 2009-03-04 00:32:30
我認爲「深層次」的原因是因爲它不允許在縮小時進行賦值:byte = int是不允許的,int也是double。會做一個簡單的字節a; a + = 2;並且不能編譯,人們會在java上扔鞋子。但我仍然會喜歡額外的規則,使其工作沒有演員:( – 2009-03-04 01:20:45