Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0090 Autoboxing and Auto-unboxing

Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed. For example, the following code constructs an Integer object that has the value 100: public class Main { public static void main(String[] argv) { Integer iOb = 100; // autobox an int } } To unbox an object, simply assign that object reference to a primitive-type variable. For example, to unbox iOb, you can use this line: public class Main { public static void main(String[] argv) { Integer iOb = 100; // autobox an int int i = iOb; // auto-unbox } } Here is a program using autoboxing/unboxing: public class Main { public static void main(String args[]) { Integer iOb = 100; // autobox an int int i = iOb; // auto-unbox System.out.println(i + " " + iOb); // displays 100 100 } } Output: 100 100