Search This Blog

Autoboxing & Unboxing in Java

Autoboxing and unboxing is introduced in java with java 5.Lets consider one example to understand these terms. Check the below code and think if it will compile or not...
int sum(int a, int b){
return a+b;
}
Integer I =sum(3,4);
In the above example if you will try to compile  it with java 1.4 or below you will see compile error. Compiler will complain about return type of method "sum" and the type of variable "I" as methid is returning primitive datatype where as Integer is a wrapper class for int. But the same code will compile and run fine with java 5 because of the functionality called autoboxing. In autoboxing compiler converts primitive datatype to corresponding object wrapper class eg. int to Integer, char to Character etc.
The java compiler applies autoboxing when a primitive type value is
  • Assigned to a variable of the corresponding wrapper class. 
  • Passed as a parameter to a method which is expecting input parameter as corresponding  wrapper class.

Good use of autoboxing/unboxing is there with Generics where we define a collection of certain type(some wrapper class object) and add primitive type data to it. Refer below example
List<Integer> lst=new ArrayList();
lst.add(5);
On similar path converting wrapper type object to its corresponding primitive type is known as unboxing in java.

No comments:

Post a Comment