Java – what happens when we add two integer objects?
•
Java
When we add two integer objects to Java, can anyone explain the internal behavior? (just like un@R_778_2419 @Object to a primitive, then add two integers, and finally wrap them in an integer object)
Integer sum = new Integer(2) + new Integer(4);
Solution
It compiles into:
Integer sum = Integer.valueOf(new Integer(2).intValue()+new Integer(4).intValue());
You can verify this by looking at the bytecode disassembly obtained using javap - C
This corresponds to the new integer (2) Part of intvalue(), leaving int 2 in the stack:
0: new #2; //class java/lang/Integer 3: dup 4: iconst_2 5: invokespecial #3; //Method java/lang/Integer."<init>":(I)V 8: invokevirtual #4; //Method java/lang/Integer.intValue:()I
This is with the new integer (4) For the part corresponding to intvalue(), put int 4 on the stack:
11: new #2; //class java/lang/Integer 14: dup 15: iconst_4 16: invokespecial #3; //Method java/lang/Integer."<init>":(I)V 19: invokevirtual #4; //Method java/lang/Integer.intValue:()I
And here and 2 are calculated with Iadd by calling integer Valueof wraps the sum as an integer and stores the result in the first local variable (astore_1):
22: iadd 23: invokestatic #5; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 26: astore_1
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码