Boxing is to place a primitive data-type within an object so that the primitive can be used like an object. For example, a List, prior to JDK 1.5, can't store primitive data types. So, to store int type data in a List, a manual boxing was required (i.e from int to integer). Similarly, to retrieve the data back, an unboxing process was required to convert Integer back to int.
Autoboxing is the term for treating a primitive type as an object type. The compiler automatically supplies the extra code needed to perform the type conversion. For example, in JDK 1.5, it now allows the programmer to create an ArrayList
of int
s. This does not contradict what was said above for List
: the ArrayList
still only lists objects, and it cannot list primitive types. But now, when Java expects an object but receives a primitive type, it immediately converts that primitive type to an object.
This action is called Autoboxing, because it is boxing that is done automatically and implicitly instead of requiring the programmer to do so manually.
Unboxing is the term for treating an object type as a primitive type without any extra code.For example, in versions of Java prior to 1.5, the following code did not compile:
Integer i = new Integer(9);Originally, the compiler would not accept the last line. As
Integer j = new Integer(13);
Integer k = i + j; // error prior to JDK 1.5
Integer
s are objects, mathematical operators such as +
were not meaningfully defined for them. But the following code would of course be accepted without complaint:int i = 9;
int j = 13;
int k = i + j;
int x = 4;The
int y = 5;
// Integer qBox = new Integer(x + y);
Integer qBox = x + y;//would have been error,but okay now-equi to prev line
Integer
is unboxed into an int
, the two are added, and then the sum is autoboxed into a new Integer
.Pros and Cons:
- Autoboxing unclutters your code, but comes with important considerations in terms of performance and sometimes unexpected behavior.
- Understand what == means. For objects, you are comparing identity, for primitive types, you are comparing value. In the case of auto-unboxing, the value based comparison happens.
- If the Integer object is null, assigning in to int will result in a runtime exception – NullPointerException – being thrown.
1 comment:
Hi,
Autoboxing is a great feature provided by JAVA5 but using it blindly may result in very subtle problem which will take hours and hours to
debug and find. to read more see the link
What is the problem while using '==' in autoboxing world in Java 5 ?
Thanks
Javin
Post a Comment