What is AutoBoxing and Unboxing?

Autoboxing and Unboxing is a feature introduced in Java version 5.

This feature is related to conversion between primitive data types to its corresponding Wrapper class Type.

For example, converting automatically from int to Integer object is considered as Autoboxing, where as automatically converting Integer object to int is called Auto unboxing. No code need to be written, explicitly for this conversion.

public class AutoBoxingUnboxing {
	public static void main(String args[])
	{
	//auto boxing, automatically converts int to Integer
	Integer iObj = 10;

	Integer iObj1 = new Integer(20);

	//auto unboxing, automatically converts
	int i = iObj1;

	display(1.1f, 2.2f);
	}

	static void display(Float val1, Float val2)
	{
	System.out.println("Display(): "+val1+" "+val2);
	}
}

Output:
Display(): 1.1 2.2

Autoboxing and Unboxing happens, when below operations are done
1.during comparison
2.assignment
3.returning from a method

public class AutoBoxing1 {
	public static void main(String args[])
	{
		Integer val1=12;

		//Here val1 is automatically converted to primitive type int
		//after above conversion, comparison is done
		if(val1<6)
		{
			System.out.println("12 is less than 6");
		}
		else
		{
			System.out.println("12 is not less than 6");
		}
	}
}
output:
12 is not less than 6

Auto Boxing and Unboxing occurs between below types

Basic Data Type Wrapper Type
int java.lang.Integer
float java.lang.Float
short java.lang.Short
byte java.lang.Byte
long java.lang.Long
double java.lang.Double
char java.lang.Character
boolean java.lang.Boolean

You may also like to read:
Basic data types in Java
Purpose of Generic Class
How to create Thread using anonymous class

One thought on “What is AutoBoxing and Unboxing?”

Leave a Reply