Wrapper Class in Java


In Java programming language the wrapper class is used to convert primitive into an object and object to primitive. There is a concept that is autoboxing which is defined as the automatic conversion of primitive into an object. There is another concept known as unboxing which is defined as the automatic conversion of an object into primitive.

The eight wrapper classes are those that are in the java. lang package. The following are the eight wrapper classes:

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


Wrapper class Example: Primitive to Wrapper:

Consider the following example to convert primitive to wrapper:

CODE:

public class ExampleWrapper {

public static void main (String args []) {

int x = 34;

Integer a = Integer. valueOf (x);

Integer b = x;

system. out. println (x+ “” + a + “” + b);

}}

OUTPUT:

34 34 34

In the above example we converted int to integer and used autoboxing at line Integer b = x;


Wrapper class Example: Wrapper to Primitive:

Consider the following example to convert wrapper to primitive:

CODE:

public class ExampleWrapper {

public static void main (String args []) {

Integer x = new Integer (4);

int a = x. intValue ();

Integer b = x;

system. out. println (x+ “” + a + “” + b);

OUTPUT:

4 4 4

In the above example we converted integer to int and used unboxing at line Integer b = x;