Java Wrapper classes

Facebooktwitterredditpinterestlinkedinmailby feather

Java Wrapper classes

A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects.

Wrapper class facilitates with conversion mechanism that converts primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature is used for conversion. Converting primitive data type into an object is called autoboxing and converting wrapper object into primitive data type is called unboxing.

All the wrapper classes like Integer, Float, Long, Byte, Double, Short are subclasses of the abstract class Number.

Here is a list of all eight Wrapper classes. These classes belong to a java.lang package.

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

Example1

Output

In the given example, compiler will write the Integer.valueOf(n) internally and convert int n into wrapper class Integer. It is called autoboxing.

Example2

Output

In the given example, the compiler will write n.intValue() internally to convert Wrapper class to primitive data type.  It is called unboxing.

Facebooktwitterredditpinterestlinkedinmailby feather