Tutorials

Java Wrapper Class


Java Wrapper Class


Wrapper classes in java provide a process to ‘wrap’ primitive values in objects. This allows primitive values to enjoy the privileges offered to the java objects.

 

Before java 5, programmers were required to do autoboxing and unboxing manually. But with introduction of autoboxing and unboxing in java 5, most of the tasks are automatically handled.

Wrapper objects are immutable like String.

 

The automatic conversion of primitive types into objects is referred as autoboxing.

The automatic conversion of objects into primitive types is referred as unboxing.

Java provides a wrapper class for every primitive type.

 

Given below is the chart showing primitive and their corresponding wrapper class:

Primitive

Wrapper Class

boolean

Boolean

byte

Byte

char

Character

double

Double

float

Float

int

Integer

long

Long

short

Short

All the wrapper classes given in the chart like Boolean, Byte, Float, Double, etc. are immutable and final.

Convert Primitive to Wrapper in java

This process of conversion of primitive type to object (wrapper class) is known as autoboxing.

Even though these conversions are automatically performed in latest versions of java but still we must see how it can be achieved manually. For the demonstration purpose we will use below example:

public class WrapperExample1 {

	public static void main(String[] args) {
		int num = 100;
		Integer wrapperNum = Integer.valueOf(num); //primitive to wrapper
		Integer autoWrapperNum = num; //autoboxing:compiler does the above conversion automatically

		System.out.println(num+" "+wrapperNum+" "+autoWrapperNum);
	}

}

OUTPUT:

100 100 100

 

Convert Wrapper to Primitive in java

The process of conversion of object (wrapper class) to primitive type is known as unboxing.

These conversions are automatically performed in latest version of java. But for learning purpose we will see the manual process of achieving the same. Look at the below given example:

public class WrapperExample2 {

	public static void main(String[] args) {
		Integer num = new Integer(100);
		int primitiveNum = num.intValue();//convert wrapper to primitive type
		int autoPrimNum = num;//unboxing:compiler performs conversion process automatically 
		
		System.out.println(num+ " "+primitiveNum+" "+autoPrimNum);

	}

}

OUTPUT:

100 100 100

 



Please Share this page
Views : 161
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!