Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Boxing and AutoBoxing in Java?

Tags:

java

boxing

What is the difference between Boxing and AutoBoxing in Java? Several Java Certification books use two such terms. Do they refer to the same thing that is Boxing?

like image 511
kauray Avatar asked Nov 24 '15 14:11

kauray


People also ask

What is Autoboxing also called?

Autoboxing, also known as unboxing, in Java is the process of converting primitives to their primitive wrapper types and vice versa.

Is wrapping and boxing same in Java?

Wrapper classes in java provides a mechanism to convert primitive into object and object into primitive. Whereas automatic boxing and unboxing allows you to do that conversion automatically.

Why do we need Autoboxing in Java?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

What is Java unboxing?

Unboxing in Java is an automatic conversion of an object of a wrapper class to the value of its respective primitive data type by the compiler. It is the opposite technique of Autoboxing. For example converting Integer class to int datatype, converting Double class into double data type, etc.


2 Answers

Boxing is the mechanism (ie, from int to Integer); autoboxing is the feature of the compiler by which it generates boxing code for you.

For instance, if you write in code:

// list is a List<Integer>
list.add(3);

then the compiler automatically generates the boxing code for you; the "end result" in code will be:

list.add(Integer.valueOf(3));

A note about why Integer.valueOf() and not new Integer(): basically, because the JLS says so :) Quoting section 5.1.7:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

And you cannot enforce this requirement if you use a "mere" constructor. A factory method, such as Integer.valueOf(), can.

like image 53
fge Avatar answered Oct 21 '22 11:10

fge


In my understanding, "Boxing" means "explicitly constructing a wrapper around a primitive value". For example:

int x = 5;
Integer y = new Integer(x); //or Integer.valueOf(x);

Meanwhile, "Autoboxing" means "implicitly constructing a wrapper around a primitive value". For example:

Integer x = 5;
like image 24
Konstantin Yovkov Avatar answered Oct 21 '22 10:10

Konstantin Yovkov