正如大家已经说过的那样, += 有一个隐式转换。为了帮助说明这一点,我将使用我不久前编写的一个非常适合这类问题的应用程序。这是一个在线反汇编程序,因此您可以查看正在生成的实际字节码: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)