Java - Autoboxing & Unboxing

Java - Autoboxing & Unboxing

  • autoboxing is used to convert primitive data types to their wrapper class objects
  • unboxing is used to convert wrapper class objects to their primitive data types

When Does Autoboxing and Unboxing Happen

compile time

Example Autoboxing and Unboxing

Autoboxing ExampleUnboxing Example
Integer number = 100;

compiles to

Integer number = Integer.valueOf(100);
Integer num2 = new Integer(50); 
int inum = num2;

compiles to

Integer num2 = new Integer(50);
int inum = num2.intValue();

What Data Gets Autoboxed and Unboxed

Primitive TypeWrapper Class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble

Things to be Aware Of

Do not mix primitives and objects while doing comparisons

public static void main(String []args){
	System.out.println(
		((Integer) 0) == ((Integer) 0)
	);
	System.out.println(
		((Integer) 100000) == ((Integer) 100000)
	);
}


// would print out
// true
// false