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?
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.
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
Change values from Primitive value to Wrapper Class Values in java example
Integer a = 10;
int b = a;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.