Friday, July 12, 2013

3. What's AutoBoxing in Java?

AutoBoxing was introduced in Java 5 (previously Java 1.5)

AutoBoxing is a feature of Java that automatically casts or converts a primitive data type to an equivalent object reference data type, un-boxing as you must have guessed by now is the reverse.

For example,

int -> Integer casting is called Auto Boxing
Integer -> int casting is called Auto Unboxing

This feature was introduced to eliminate the obvious conversion from primitive datatypes and object reference (wrapper) datatypes in certain operations with collections such as arraylist etc. Since the introduction of autoboxing one need not explicitly specify or cast int to Integer and vice versa.

Example:

ArrayList<Integer> myIntList = new ArrayList<Integer>();
myIntList.add(1);  

/*Argument 1 [in myIntList.add(1)] is of primitive type"int" whereas arrayList element is of wrapper type "Integer" the casting from int to Integer occurs automatically by the Autoboxing feature */

myIntList.add(2); 

All primitive types e.g. byte, short, char, int, long, float, double and boolean has corresponding wrapper class e.g. Byte, Short, Integer, Character etc and participate in autoboxing and unboxing. Since whole process happens automatically without writing any code for conversion its called autoboxing and auto unboxing.

No comments :

Post a Comment