Java Wrapper Classes Explained

What exactly is a Java Wrapper Class? We are very familiar with primitive data types like int, short, long, float, etc. Each of the primitive data types is associated with a wrapper class. You are essentially wrapping a class around a primitive data type. The table below shows the primitive data type and its wrapper class counterpart.

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


Wrapper Class Purpose

The wrapper class in Java provides the ability to convert a primitive data type into an object. You can also convert an object back into a primitive data type. These two processes are defined as autoboxing and unboxing.


Wrapper Class Autoboxing Sample Code

Converting a primitive data type to a class object is what is known as autoboxing.

package com.jcd.java.tutorials;

public class JavaWrapperClass 
{

	public static void main(String[] args) 
	{	
		//Let's define an integer and give a value of 100  
		int jcdInt = 100;  
		
		//Let's wrap the integer in the Integer Class
		Integer jcdIntegerClass1 = Integer.valueOf(jcdInt);
		
		//Let's define a new Integer Class and set it to jcdInt 
		Integer jcdIntegerClass2 = jcdInt;
		  
		System.out.println("jcdInt: "+jcdInt); 
		System.out.println("jcdIntegerClass1: "+jcdIntegerClass1);
		System.out.println("jcdIntegerClass2: "+jcdIntegerClass2);
	}

}


Wrapper Class Autoboxing Output

jcdInt: 100
jcdIntegerClass1: 100
jcdIntegerClass2: 100


Wrapper Class Unboxing Sample Code

Converting a class object to a primitive data type what is known as unboxing.

package com.jcd.java.tutorials;

public class JavaWrapperClass 
{

	public static void main(String[] args) 
	{
		//Let's define an Integer Class with a value of 100
		Integer jcdIntegerClass3 = new Integer(100);    
		
		//Let's convert the Integer Class to a primitive data type
		int jcdInt1 = jcdIntegerClass3.intValue();  
		
		//Le'ts create a new primitive and assign it the 
		int jcdInt2 = jcdIntegerClass3;
		    
		System.out.println("jcdIntegerClass3: "+jcdIntegerClass3);
		System.out.println("jcdInt1: "+jcdInt1);
		System.out.println("jcdInt2: "+jcdInt2);
	}

}


Wrapper Class Unboxing Output

jcdIntegerClass3: 100
jcdInt1: 100
jcdInt2: 100


Add a Comment

Your email address will not be published. Required fields are marked *