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 Example | Unboxing 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 Type | Wrapper Class |
---|---|
boolean | Boolean |
byte | Byte |
char | Character |
float | Float |
int | Integer |
long | Long |
short | Short |
double | Double |
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
, multiple selections available,