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?
Autoboxing, also known as unboxing, in Java is the process of converting primitives to their primitive wrapper types and vice versa.
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With