0

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?

ihavename
  • 25
  • 7

2 Answers2

2

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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.

Kushagra Misra
  • 461
  • 1
  • 7
  • 15