Java - Autoboxing and Unboxing

What is Autoboxing and Unboxing?

AutoBoxing and unboxing work with primitive data types and their corresponding wrapper classes.

The automatic wrapping from a primitive data type (byte, short, int, long, float, double, char and boolean) to its corresponding wrapper object (Byte, Integer, Long, Float, Double, Character and Boolean) is called autoboxing.

The reverse, unwrapping from wrapper object to its corresponding primitive data type, is called unboxing.

With autoboxing/unboxing, you can do the following.

Integer n = 200; // Boxing
int a = n;       // Unboxing

The compiler will replace the above statement with the following:

Integer n = Integer.valueOf(200);
int a = n.intValue();

Null Values

Primitive types cannot have a null value assigned to them, whereas reference types can have a null value.

The boxing and unboxing happens between primitive types and reference types.

Integer n = null; // n can be assigned a null value
int a = n;        // will throw NullPointerException at run time

Demo

public class Main {
  public static void main(String[] args) {
    Integer n = Integer.valueOf(200);
    int a = n.intValue();

    System.out.println(a);/*from   w w w.j a  v  a  2s . c  o  m*/
    System.out.println(n);

  }
}

Result

Related Topics

Quiz