5.13.5. Boxing

There are places where Java requires a class because it needs to make use of an object reference. We will see class LinkedList, whose instances are lists of object. Instances of type LinkedList<String> are lists of string objects. But you are not allowed to use class LinkedList<int> because int is a primitive type, not a class, and values of type int are not references.

Java gets around that problem by having a class for every primitive type. For example, the class associated with type int is called Integer. You are allowed to use type LinkedList<Integer>.

An object of class Integer holds one value of type int. If n has type int, then statement

  Integer nn = new Integer(n);
creates an Integer object holding the value of n. Then statement
  int x = nn.intValue();
gets the integer stored in nn.

The operation of converting from int to Integer is called boxing, and the operation of converting from Integer to int is called unboxing.

Java does boxing and unboxing conversions automatically. For example, if an int occurs in a place where an object of class Integer is required, the int is automatically converted to Integer. Similarly, if an Integer object occurs where a value of type int is needed, it is converted automatically to type int.

The following table list the classes that correspond to primitive types.

Long

Corresponds to long.

Integer

Corresponds to int.

Short

Corresponds to short.

Byte

Corresponds to byte.

Double

Corresponds to double.

Float

Corresponds to float.

Boolean

Corresponds to boolean.