0

I found an example where I cannot find the number of boxing and unboxing in the Java code below :

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

I would say that there is one type of unboxing (int y = x + x), but I am not sure about that. Is there any boxing as well?

azro
  • 53,056
  • 7
  • 34
  • 70
ihavename
  • 25
  • 7

3 Answers3

4

There is one boxing in Integer x = 5. The int 5 is boxed to Integer.

There are two un-boxings in int y = x + x: Integer x is unboxed twice.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

There is only boxing

Integer x = 5

From Docs:

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

Why? Because we are reference only once And there are two unboxing in :

int y = x + x

From Docs

If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()

Why? Because we are calling two times x.IntValue()

Following this docs from Boxing and Unboxing

Gatusko
  • 2,503
  • 1
  • 17
  • 25
0

Change values from Primitive value to Wrapper Class Values in java example

Integer a = 10;
int b = a;

https://youtu.be/96pq0mpFz9M

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
  • Welcome to Stack Overflow and thanks for your contribution! It would be nice if you would read this guide [How to write a good answer](https://stackoverflow.com/help/how-to-answer) and adjust your answer accordingly. In detail you should write the essential explanation as text here and not linking it as video. When you're so kind to do it you can also remove the video-link. Thanks! – David Apr 07 '19 at 07:12