ihavename
ihavename

Reputation: 25

Java boxing and unboxing

I have an example in which I cannot determine the number of boxing(s) and unboxing(s), which taking place in the Java code below :

int x = 5;
Integer y = x + x;

From my point of view I see one type of boxing (Integer y = x + x). Am I wrong? Is there any unboxing as well?

Upvotes: 0

Views: 493

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

There is no unboxing. Just boxing happening.

First the expression x+x calculated which is an int and that is boxed to Integer.

So in the whole statement there is no conversion of Integer to int, hence no unboxing.

Upvotes: 2

Kushagra Misra
Kushagra Misra

Reputation: 481

As per your question we first define an int value and assign it to x variable (no boxing un-boxing required), Then you are adding 2 integer variable no boxing un-boxing required. Now you are assigning a int result to Integer means changing from primitive to non primitive data type. Java autoboxing can convert int to integer there here autoboxing is there which is boxing.

Upvotes: 1

Related Questions