Java wrapper classes – Tutorial with Examples

Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes.

Below table shows the primitive types and their wrapper classes in java.

Primitive typeWrapper classConstructor Arguments
byteBytebyte or String
shortShortshort or String
intIntegerint or String
longLonglong or String
floatFloatfloat, double or String
doubleDoubledouble or String
charCharacterchar
booleanBooleanboolean or String

Why Wrapper Classes

I think it was a smart decision to keep primitive types and Wrapper classes separate to keep things simple. We need wrapper classes when we need a type that will fit in the Object world programming like Collection classes. We use primitive types when we want things to be simple.

Primitive types can’t be null but wrapper classes can be null.

Wrapper classes can be used to achieve polymorphism.

Here is a simple program showing different aspects of java wrapper classes.

package com.journaldev.misc;

import java.util.ArrayList;
import java.util.List;

public class WrapperClasses {

    private static void doSomething(Object obj){
        
    }
    
    public static void main(String args[]){
        int i = 10;
        char c = 'a';
        
        //primitives are simple to use
        int j = i+3;
        
        //polymorphism achieved by Wrapper classes, we can't pass primitive here
        doSomething(new Character(c));
        
        List<Integer> list = new ArrayList<Integer>();
        //wrapper classes can be used in Collections
        Integer in = new Integer(i);
        list.add(in);
        
        //autoboxing takes care of primitive to wrapper class conversion
        list.add(j);
        
        //wrapper classes can be null
        in = null;
    }
}
Facebooktwittergoogle_plusredditmailFacebooktwittergoogle_plusredditmail

Leave a Reply

Your email address will not be published. For posting CODE wrap them inside <pre class="prettyprint"></pre>. Required fields are marked *