我對下面的代碼有疑問。代碼取自我的Programming Language書。Java byte to int強制
byte x, y, z;
...
/* The values of y and z are coerced into int and int addition is performed */
/* The sum is converted into byte */
x = y + z;
我的問題是爲什麼Java做這樣的強制。你有什麼想法?
在此先感謝。
我對下面的代碼有疑問。代碼取自我的Programming Language書。Java byte to int強制
byte x, y, z;
...
/* The values of y and z are coerced into int and int addition is performed */
/* The sum is converted into byte */
x = y + z;
我的問題是爲什麼Java做這樣的強制。你有什麼想法?
在此先感謝。
在JVM中,每個堆棧元素的大小都是32位。實際添加量是這樣的:
int
)iadd
指令被調用,它從棧中彈出兩個值,並增加了他們這就是爲什麼你所得到的值(int
型)再次轉換爲byte
。
爲了簡化JVM指令集,它不爲每個整型類型實現一個加法運算符。具體來說,它不能添加字節。 (請參閱the list of JVM ops)這使得JVM更簡單,並且可能更便於攜帶。
這反映了java字節碼,jvm,java虛擬機,它在規範中使用int來在堆棧中存儲單個字節變量。它使用iadd
添加兩個字節。請參閱jvm instruction set。
有人可能會爭辯說它有點過分規定:提到參考實現的實現選擇。
可以得到的答案是JLS這樣說。 –
這是因爲這就是JVM的工作原理(它不能在字節上添加):http://stackoverflow.com/questions/18483470/is-addition-of-byte-converts-to-int-is-because-of -java-language-rules-or-because – birryree
我知道y和z在添加時會變成整數,但是不會將其設置回x會導致編譯錯誤而無法投射? – whiskeyspider