Table of Contents

Data Type - Boxing (Autoboxing|Autowrapping) and Primitive Wrapper

About

Boxing and Unboxing are the terms used to describe automatically wrapping a primitive type in a wrapper class and unwrapping it as necessary.

This operation has the advantage to add basic method functions (such as toUpperCase, length, …).

The wrapper classes for primitive types have generally the first letter as uppercase to differentiate them from the primitive one. For instance, String for string.

The code will continue to work - no matter if it's a primitive type or wrapper class thanks to autoboxing.

The term autowrapping would be more consistent, but the “boxing” metaphor was taken from C#.

Boxing and unboxing is a courtesy of the compiler. The compiler inserts the necessary calls when it generates the instructions.

Example

Ex with Java, the following class are the wrappers:

Integer i = 10;
// Is like saying:
Integer i = Integer.valueOf(10);
String foo = "nico";
// Is like saying:
String foo = new String("nico");

Primitive types vs wrapper

Use the primitive types where there is no need for objects for the following reasons.

If we are autoboxing some value to one of the wrapper classes (Boolean, Byte, Short, Char, Integer, Long), the compiler sometimes creates a new object and sometimes uses the pool of values, similarly like with Strings.

Here are some rules as with Java 5 :

Property

Generally, the wrapper classes are:

Documentation / Reference