正如每个人都已经说过的那样,+ =有一个隐含的强制转换。为了说明这一点,我将使用一个我后来写的应用程序,这对于这些类型的问题来说是完美的。这是一个在线的反汇编,以便您可以检查出真实而产生的实际字节码: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