Wrapper Class in Java

I will tell you here what is wrapper class in Java. The primitive data types are not objects; so they do not belong to any class; they are defined in the language itself.

Sometimes, it is required to convert data type into an object in Java language. For example, up to JDK 1.4, the data structure accepts only objects to store.

A data type needs to be converted into an object and then added to a Collection. For this conversion, the concept of wrapper class came into an existence.

As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance.

Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type.

For example,

int x = 50;
Integer i = new Integer(x);

The int data type x is converted into an object to a variable i using Integer class. The i object can be used in Java programming wherever x is required an object.

The following code can be used to unwrap (getting int back from Integer object) the object i.

int y = i.intValue();
System.out.println(y); // prints 50

intValue() is a method of Integer class that returns an int value.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *