Autoboxing and auto-unboxing

Type Wrappers

Java uses primitive types, such as int or double, to hold the basic primitive data types. Primitive types, rather than objects, are used for the sake of performance.

Java provides type wrappers, which are classes that encapsulate a primitive type within an object.

The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean.

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
Home 
  Java Book 
    Language Basics  

Autoboxing Autounboxing:
  1. Autoboxing and auto-unboxing
  2. Autoboxing and Methods
  3. Autoboxing/Unboxing in Expressions