INTRODUCTION:
The automatic conversion made by the Java compiler between primitive types and their corresponding object wrapper classes, is known as Autoboxing
It allows us to use primitive and object type interchangeably in Java on many places like assignment, method invocation etc
For example
A primitive type like int gets automatically converted into corresponding wrapper class object e.g. Integer
because primitive is boxed into wrapper class.
If the conversion goes the other way, this is called unboxing. Ex.: If Integer object is converted into primitive int.
Benefits of Autoboxing & Unboxing:
- Less coding is required since there is no need of conversion between primitives and Wrappers manually
- Autoboxing makes working with the Collections Framework much easier.
- With autoboxing it is no longer necessary to manually construct an object in order to wrap a primitive type.
- It helps prevent errors, but may lead to unexpected errors hence should be used carefully.
Example for Autoboxing :
class Example1{
public static void main(String args[]){
int a=10;
Integer a2=new Integer(a);//Boxing
Integer a3=8;//Boxing
System.out.println("values wil be" + a2+" "+a3);
}
}
Output: 10 8
Example for unboxing:
class Example2{
public static void main(String args[]){
Integer i=new Integer(100);
int a=i;
System.out.println(a);
}
}
output: 100
References:
http://www.javatpoint.com/autoboxing-and-unboxing
0 Comment(s)