Java-Autoboxing-and-Unboxing
Autoboxing and unboxing is introduced in Java1.5 to automatically convert primitive type into boxed primitive(Object or Wrapper class).Autoboxing allows you to use primitive and object type interchangeably in Java on many place like assignment,method invocation.
If you hava been using Collecions like HashMap or ArrayList before Java 1.5 then you are familiar with the issues like you can not directly put primitives into Collections, instead you first need to convert them into Object only then only you can put them into Collections. Wrapper class like Integer, Double and Boolean helps for converting primitive to Object but that clutter the code. With the introduction of autoboxing and unboxing in Java this primitive to object conversion happens automatically by Java compiler which makes code more readable.But autoboxing and unboxing comes with certain caveats which needs to be understood before using them in production code and it becomes even more important because they are automatic and can create subtle bugs if you are not sure when autoboxing in Java code occurs and when unboxing happens.
What is autoboxing and unboxing in Java
autoboxing and unboxing :converts a primitive type like int into corresponding wrapper class object e.g. Integer.opposite case is called unboxing
Primitive type | Wrapper class |
---|---|
bollean | Boolean |
byte | Byte |
char | Character |
float | Float |
int | Integer |
long | Long |
short | Short |
double | Double |
When does autoboxing and unboxing occurs in Java
1 | //before autoboxing |
Unnecessary Object creation due to Autoboxing in Java
One of the danger of autoboxing is throw away object which gets created if autoboxing occurs in a loop.Here is an example of how unnecessary object can slow down your application:1
2
3Integer sum=0
for(int i=1000;i<5000;i++)
sum+=i;
In this code sum+=i
will expand as sum=sum+i
and since + operator is not applicable to Integer object it will trigger unboxing of sum Integer object and then autoboxing of result which will be stored in sum which is Integer as shown below :1
2sum = sum.intValue() + i;
Integer sum = new Integer(result);
here since sum is Integer, it will create around 4000 unnecessary Intger object which are just throw away and if this happens on large scale has It potential to slow down system with frequent GC for arithmetic calculation always prefer primitive over boxed primitive and look for unintentional autoboxing in Java.