简体   繁体   中英

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?

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 .

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM