Monday, March 7, 2016

What is wrapper class?

Wrapper class is any class which "wraps" the functionality of another class or component. Specifically, primitive wrapper class in the Java is one of eight classes to provide object methods for primitive types.

Wrapper classes are used to represent primitive values when an object is required.

Primitive types:
byte
short
int
long
float
double
char
boolean

Wrapper classes:
Byte
Short
Integer
Long
Float
Double
Character
Boolean

Basically, by capitalize the first letter of the name of the primitive type, we can get the wrapper class for it. (e.g. byte --> Byte)

Wrapper classes are used as follows:
int i = 0;
Integer i2 = new Integer(i);

For example, primitive types can not be used for the argument for the following methond:
void methodA(Object obj){
   //Do something
}
In this case, by wrapping the value by the wrapper class, the method above can be used:
int i = 0;
Integer i2 = new Integer(i); 
void methodA(Object obj){ //i2 can be used for this argument
 
}
Moreover, wrapper classes have multiple useful methods like "Integer.valueOf()" or "Integer.parseInt()"