Wrapper classes in Java with Examples

In Java, which is an Object Oriented Programming Language, everything revolves around Classes and Objects.

Java’s Collection Framework is a collection of rich sets of  data structures and various useful algorithms to manipulate different Data structures in it. Java’s mostly used primary operations are performed on built in data types like int, float double etc…. However, Java Collection Framework works only on Objects. to leverage the advantage of Collection Framework to these primary data types, we have Wrapper classes for each primary data type.

In Java we have 8 primitive types. They are byte, short, int, long, float, double, char and boolean. To leverage the Object Oriented advantages, Java introduced Wrapper classes for these Primitive types.

Below are the list of primitive types and their Wrapper classes

Primitive TypeWrapper Class

So, in short, Wrapper Classes are used to convert primitive data types into objects and vice versa.

Let’s have a quick look with some Java code example on Wrapper classes

// Converting primitive types to Wrapper classes Example
int i = 12;
Integer intWrapper = new Integer(i);

float f = 512.32f;
Float floatWrapper = new Float(f);

char c = 's';
Character charWrapper = new Character(c);
// Converting primitive types to Wrapper classes Example
Integer in=new Integer(3); 
int i = in.intValue();

Character ch=new Character('s'); 
char c = ch.charValue();

Double db = new Double(5.99);
double d = db.doubleValue();

In Above Wrapper classes conversion example, we explicitly converted primitive types to Wrapper classes and Wrapper classes to Primitive Type. Java 5 Introduced New feature called AutoBoxing and Unboxing.

AutoBoxing and UnBoxing

,In Java Automatic Conversion of Primitive types into Wrapper Classes is called AutoBoxing. Here user no need to explicitly code to get the primitive value from corresponding Wrapper class In the same way If Java Compiler converts Wrapper classes to their corresponding primitive types, it is called Unboxing.

Let’s have a simple quick example of AutoBoxing and Unboxing in Java

//Blow AutoBxing, Compiler coverts automatically for us
int a = 12;  
Integer intObject = a;

//Blow UnBoxing, Compiler coverts automatically for us
Integer in=new Integer(3); 
int i = in;

Above is brief introduction of Wrapper classes for beginners. Please let me know In comments If you need anything else to be explained or need more details.

Leave a Reply
