Wrapper Classes

In Java we have eight primitive data types byte, short, int, long, float, double, char and boolean are not objects, Wrapper classes are used for converting primitive data types into objects, like int to Integer, double to Double, float to Float and so on. Let’s take a simple example to understand why we need wrapper class in java.

For example: While working with collections in Java, we use generics for type safety like this: ArrayList<Integer> instead of this ArrayList<int>. The Integer is a wrapper class of int primitive type. We use wrapper class in this case because generics needs objects not primitives. There are several other reasons you would prefer a wrapper class instead of primitive type, we will discuss them as well in this article.

Primitive Data Type Corresponding Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
Double double

Need of wrapper classes

As I mentioned above, one of the reason why we need wrapper is to use them in collections API. On the other hand, the wrapper objects hold much more memory compared to primitive types. So use primitive types when you need efficiency and use wrapper class when you need objects instead of primitive types.

The primitive data types are not objects so they do not belong to any class. While storing in data structures which support only objects, it is required to convert the primitive type to object first which we can do by using wrapper classes.

Example:


    HashMap<Integer, String> hm = new HashMap<Integer, String>();

So for type safety we use wrapper classes. This way we are ensuring that this HashMap keys would be of integer type and values would be of string type.
Wrapper class objects allow null values while primitive data type doesn’t allow it.

Example 1: Converting a primitive type to Wrapper object

public class WrapperClassExample1 {  
    public static void main(String args[]) {  
        //Converting int primitive into Integer object  
        int value = 100;  
        Integer reference = Integer.valueOf(value);  
    
        System.out.println(value+ " "+ reference);  
    }
}

In the above program we're converting the primitive to wrapper, this convertion is called as autoboxing

Example 2: Converting Wrapper object to Primitive

public class WrapperClassExample2 {  
    public static void main(String args[]) {  
        //Converting Integer object to primitive  
        Integer integerObj = new Integer(100);  
        
        int value = integerObj.intValue();  
        
        System.out.println(value+ " "+ integerObj);  
    }
}

In the above program we're converting the wrapper object to primitive, this convertion is called as unboxing