Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
So why do we need it and why do we use autoboxing and unboxing in Java?
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of
Object
and can not be overridden.we have primitives like
int
for performance reasons, and theObject
alternatives likeInteger
for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE andInteger.toString(int)
).The OO benefits are visible most easily with Generics (
List<Integer>
), but are not limited to that, for example:Auto Boxing is used to convert primitive data types to their wrapper class objects. Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
In case of Collections which work with objects only auto unboxing is used. Here's how :
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider
float
versusdouble
).On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (
Object
,String
,Integer
, etc).This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a
String
as anObject
, for example).Primitive variables aren't interchangeable in the same way, neither with each other, nor with
Object
. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition
List<T>
has a type parameterT
, which can beObject
(producing a concrete typeList<Object>
),String
(List<String>
),Integer
(List<Integer>
) and so on.Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of
List<T>
are, in fact, compiled to (the binary equivalent of)List<Object>
(for other types, the bound may be something other thanObject
, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.Putting the two together
Now the problem is the combination of the above realities: if
List<T>
becomesList<Object>
in all cases, thenT
must always be a type that can be directly assigned toObject
. Anything else can't be allowed. Since, as we said before,int
,float
anddouble
aren't interchangeable withObject
, there can't be aList<int>
,List<float>
orList<double>
(unless a significantly more complicated implementation of generics existed in the JVM).But Java offers types like
Integer
,Float
andDouble
which wrap these primitives in class instances, making them effectively substitutable asObject
, thus allowing generic types to indirectly work with the primitives as well (because you can haveList<Integer>
,List<Float>
,List<Double>
and so on).The process of creating an
Integer
from anint
, aFloat
from afloat
and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them asObject
is inconvenient, there are cases where the language does this automatically - that's called autoboxing.Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well. An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.