Sunday 22 September 2013

Wrapper Classes/Type Wrapper in java



DEFINITION :

Wrapper classes in java as the name wraps or encapsulates the primitive data types such as int, char etc. and gives them an object like appearance which is mostly used in Collections because in Collections we can only add objects. They are also known as Type Wrappers because they convert the data types into a class type.

WHY WE USE THEM?

Since java is object oriented language in which every single element should be treated as object whether it is a file, image or anything but it uses primitive data types which are not actual objects and we cannot pass them by reference, they are passed by value and also we cannot make two references which refer to same data.
Java only uses these primitive data types for performance reasons and hence there should a way in which we can convert them into objects and for this designers create
Wrapper Classes.

Basically there are two important uses of wrapper classes :

1. To convert a primitive data types into objects, that is to give them an object form.
2. To convert strings into data types which is known as the parsing operations in which various methods such as parseInt(), parseFloat() etc. are used.

LIST OF WRAPPER CLASSES :

There are 8 wrapper classes for every data type in java. They all lies in java.lang package which is implicitly imported into our programs and hence they are available without importing any package.





These eight Wrapper classes provides methods and Constructors for making the object of primitive data types and getting back the value from object.

EXAMPLE OF USE OF WRAPPER CLASSES :

Consider the code,

int i = 100;
Integer ib = new Integer(i);

In the first statement 'i' is declared as the variable of int data type and then it it Wrapped or boxed into an object of the type Integer which is a wrapper class. This is also known as
boxing.
Now, this Integer type 'ib' can be used anywhere as an object.






We can also get back the data type from the object by using the method intValue() which is static in Integer Wrapper class as :

int iu = ib.intValue();

This is known as Unwrapping or Unboxing.
There are also some constants in the wrapper classes which gives you the maximum and minimum value of data types which is defined by the language. These are :
MAX_VALUE, MIN_VALUE

Here is another example of parsing a String as an integer through the Wrapper classes.

String s = "13";
int value = Integer.parseInt(s);

The method parseInt() gives the NumberFormatException if you pass the String which has a value other than int.

In the new versions of java there is way for autoBoxing and autoUnboxing.

//AutoBoxing
int i = 100;
Integer ib = i;

//AutoUnboxing
int iu = ib;

There is large use of Wrapper classes for object conversion in Collections.
Read more