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);
The sum() method of Java Integer class numerically returns the sum of its arguments specified by a user. This method adds two integers together as per the + operator.
Integer. sum() is a built-in method in java which returns the sum of its arguments. The method adds two integers together as per the + operator.
java - A method which accepts two integer values as input parameters and returns the boolean - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With