1

guys!

How is the operator + implemented and works in Java internally in case when we add integer with Integer object?

package ru.systemres.ru;

public class Main {
    public static void main(String[] args) {
        Integer iOb = new Integer(10);
        int a = iOb + 5;
        System.out.println(a);

    }
}

Is it overloaded? Can you show me some source code from jvm which works with it? Thanks!

3 Answers 3

2

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

During Unboxing (Object(Integer) --to--> Primitive(int))

Implicitly Integer.intValue() is called to return int value.

Please Refer: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but how does it work internally step by step? Do we change + operator logic depending of the types on the left and on the right param? Or the Integer object behaves differently depending on the parameter? How does it work?
Autoboxing mainly occur in two places one is during assignment and other is during method invocation. In your case the variable is stored in primitive int a. So, the compiler is expecting primitive type here and converts the object to int in order to use it. //Internal Working Integer obj = Integer.valueOf(10); int pri = obj.intValue();
0

iOb isn't just any old object - it's an Integer. When you use it in such a context, it's outboxed to an int, and then the calculation is performed.

Comments

0

Is it overloaded? Can you show me some source code from jvm which works with it?

It is NOT overloaded, rather the Integer iOb object will be unboxed to int first and then added with 5 to the variable a.

I suggest you refer here for Autoboxing and Unboxing in Java.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.