Listen to this article

Java has numerous concepts and features. We have just touched a base on some of them such as Classes, methods, variables, Interfaces, Inheritance and more. ‘Wrapper’ class is another nice concept in Java.

What is a ‘Wrapper’ class?

Java is an Object oriented programming language. It tries to consider everything as an Object. There are many methods in Java which will take only an Object as a parameter.

So, what happens to the primitive data types? (Recall that there are 8 primitive data types in Java which are used to store values – they are int, short, byte, long, float, double, char, boolean) What if they had to be converted to an Object? This is where the concept of ‘Wrapper classes’ steps in. A ‘Wrapper class’ converts a primitive value to an Object.

There are ‘wrapper classes’ for every primitive data type:

Primitive data typeWrapper Class(available in the java.lang package)
intInteger
shortShort
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
byteByte

As we can see, ‘Integer’ is the wrapper class for the int primitive data type. The ‘Integer’ class is available in the java.lang package. In order to wrap the int data type, we use the ‘valueOf’ method instead of the constructor (as of Java versions 17)

Let us see a program to illustrate this:

 

We can see that each primitive value is converted to their corresponding Object using the wrapper classes.

There are numerous methods within each Wrapper class. Let us see some methods in the ‘Integer’ wrapper class which were also illustrated in our program:

  1. boolean equals(Object obj)

The ‘equals’ method compares the object to the specified object and returns ‘true’ if it is the same and ‘false’ if the two Objects are different.

2. String toString()

The Object is converted to a String Object.

3. static Integer valueOf(int)

The valueOf() method converts an integer datatype to an Integer Object. This is the preferred method to work with an Integer Object as the Integer constructor is likely to be deprecated soon.

Autoboxing and Unboxing:

One concept that is important with respect to Wrapper class is that of ‘Autoboxing’ and ‘Unboxing’ .

Autoboxing is when the primitive value is automatically converted to the corresponding Object by the Java compiler.

Unboxing is when the Object is automatically converted to the corresponding data type by the Java compiler

This can be illustrated by the following code:

 

We have seen ‘Wrapper Classes’ in this post.

Join me as I bring everything that we have learnt about Java tomorrow! 🙂

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 56 times, 1 visits today)

Related Posts

Leave a Reply