Can some one explain me how the internal behavior when we add two Integer objects in java? (like it is unbox Object into primitives and then add two integers and finally boxed it in to Integer object)
Integer sum = new Integer(2) + new Integer(4);
Can some one explain me how the internal behavior when we add two Integer objects in java? (like it is unbox Object into primitives and then add two integers and finally boxed it in to Integer object)
Integer sum = new Integer(2) + new Integer(4);
It's compiled into this:
Integer sum = Integer.valueOf(new Integer(2).intValue()+new Integer(4).intValue());
You can verify this by looking at the byte code disassembly obtained with javap -c
.
Here is the part that corresponds to new Integer(2).intValue(), leaving int 2 on 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
Here is the part that corresponds to new Integer(4).intValue(), leaving 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 the sum 2+4 is calculated with iadd
, the sum is boxed into an Integer by a call to Integer.valueOf
, and the result is stored in the first local variable (astore_1
):
22: iadd
23: invokestatic #5; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
26: astore_1
creation of two Integer
instances.
Auto-unboxing of those two instances.
new int
that holds the result.
Auto-boxing the result into Integer sum
instance.