Java Wrapper classes
Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper class facilitates with conversion mechanism that converts primitive into object and object into primitive. Since J2SE 5.0, autoboxing and unboxing feature is used for conversion. Converting primitive data type into an object is called autoboxing and converting wrapper object into primitive data type is called unboxing. All the wrapper classes like Integer, Float, Long, Byte, Double, Short are subclasses of the abstract class Number. Here is a list of all eight Wrapper classes. These classes belong to a java.lang package.
Primitive Type | Wrapper class |
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Autoboxing Primitive to Wrapper class public class WrapperTest1{ public static void main(String args[]){ int n=50; Integer i=Integer.valueOf(n);//converting int into Integer Integer j=50; System.out.println(n+" "+i+" "+j); }}Output
50 50 50In the given example, compiler will write the Integer.valueOf(n) internally and convert int n into wrapper class Integer. It is called autoboxing. Example2
Unboxing Wrapper class to primitive public class WrapperTest2{ public static void main(String args[]){ Integer n=new Integer(15); int i=n.intValue();//converting Integer to int int j=n; System.out.println(n+" "+i+" "+j); }}Output
15 15 15In the given example, the compiler will write n.intValue() internally to convert Wrapper class to primitive data type. It is called unboxing.