Wrappers, Auto-Boxing, AND Un-Boxing in Java

All primitive data types in Java have a corresponding wrapper classes that contains additional methods.

There are following purpose of wrapper classes

• The additional methods provided in wrapper classes are useful in manipulating the primitive data type value to some other type. For example, Integer is a wrapper for int and provide conversion methods.
• Some Java collections can not store primitives (such as ArrayList) and so primitives have to be wrapped into objects. For example,
ArrayList list = new ArrayList();
list.add(new Integer(6));



In the above code snippet, we don't have to explicitly convert int (6) to Integer class. Primitive values automatically gets converted into Integer type values. This is called Auto-Boxing.
list.add(6); //this is equivalent to list.add(new Integer(6));


Similarly converting an Integer value to int is called un-boxing (i.e. converting values to primitive types)
int num = list.get(6);
Add Comments :

Login

Register