Last Updated:

Wrapper Classes in Java - Sample Guide

Java wrapper classes are the object representation of eight primitive types in Java. All wrapper classes in Java are immutable and final. Starting with Java 5, autopacking and unpacking makes it easy to convert primitive types into their respective wrapper classes and vice versa.

The following table shows primitive types and their wrapper classes in Java

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

Why do I need wrapper classes in Java?

The developers of the Java language made a very clever decision to separate primitive types and wrapper classes, while specifying the following:

  • Use wrapper classes when working with collections.
  • Use primitive types to make your programs as simple as possible.

Another important point is that primitive types cannot be null, but wrapper classes cannot.

Shell classes can also be used to achieve polymorphism.

Here's a simple program showing various aspects of shell classes in Java:

WrapperClasses.java

package com.p-qc.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 easy to use
intj = i+3;

//polymorphism is achieved with wrapper classes, we can't use primitives 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 converting the primitive into the appropriate wrapper class
list.add(j);

//wrapper classes can be null
in = null;
}
}