ihavename
ihavename

Reputation: 25

Java boxing or unboxing

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?

Upvotes: 0

Views: 263

Answers (3)

inayat ali lakho
inayat ali lakho

Reputation: 1

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

Integer a = 10;
int b = a;

https://youtu.be/96pq0mpFz9M

Upvotes: 0

Gatusko
Gatusko

Reputation: 2598

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

Upvotes: 1

ernest_k
ernest_k

Reputation: 45309

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.

Upvotes: 4

Related Questions