Wrapper class in Java With Examples

Wrapper class in java 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 in java programs.

Wrapper Class in Java

 

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

Primitive type Wrapper class Constructor Arguments
byte Byte byte or String
short Short short or String
int Integer int or String
long Long long or String
float Float float, double or String
double Double double or String
char Character char
boolean Boolean boolean or String

Why do we need 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-Oriented 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 wrapper classes in java.

WrapperClasses.java

By admin

Leave a Reply