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

1 - 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.

3 - 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");

4 - Primitive types vs wrapper

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

  • Primitive types may be a lot faster than the corresponding wrapper types, and are never slower.
  • The immutability (can't be changed after creation) of the wrapper types may make it their use impossible.
  • There can be some unexepected behavior involving == (compare references) and .equals() (compare values).

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 :

  • autoboxing to Boolean and Byte always returns an object from the pool
  • autoboxing to Char, Short, Integer and Long returns an object from the pool when the autoboxed value is between -128 and 127 (inclusive)
  • autoboxing of Float and Double does not use the pool and always returns a new object

5 - Property

Generally, the wrapper classes are:

  • immutable: the information contained inside the wrapper can't change after the wrapper has been constructed.
  • final, so you cannot subclass them.

6 - Documentation / Reference

code/type/autoboxing.txt · Last modified: 2017/09/20 22:34 by gerardnico