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);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s compiled into this:
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:
Here is the part that corresponds to new Integer(4).intValue(), leaving int 4 on the stack:
And here the sum 2+4 is calculated with
iadd, the sum is boxed into an Integer by a call toInteger.valueOf, and the result is stored in the first local variable (astore_1):