Encapsulating a value within an object is called boxing.
Extracting a value from a type wrapper is called unboxing.
Integer iOb = new Integer(100); //box int i = iOb.intValue(); //unbox
The following code demonstrates box and unbox.
It uses a numeric type wrapper to encapsulate a value and then extract that value.
public class Main { public static void main(String args[]) { //from www .j a v a 2 s .co m Integer iOb = new Integer(100); int i = iOb.intValue(); System.out.println(i + " " + iOb); // displays 100 100 } }
Autoboxing happens when a primitive type is automatically encapsulated into its equivalent type wrapper.
Auto-unboxing happens when the value of a boxed object is automatically extracted when its value is needed.
Integer iOb = 100; // autobox an int int i = iOb; // auto-unbox
Here is the preceding program rewritten to use autoboxing/unboxing:
// Demonstrate 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 } /*from w ww . j ava2 s.c o m*/ }