Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operation inside when we add two Integer objects?

Tags:

java

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); 
like image 259
Eshan Sudharaka Avatar asked Feb 22 '12 08:02

Eshan Sudharaka


People also ask

Can you add two integer objects Java?

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.

What is integer :: sum in Java?

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.

Which of the following method definitions accepts two integer values?

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.


1 Answers

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
like image 107
Joni Avatar answered Sep 19 '22 21:09

Joni