Data Type - Boxing (Autoboxing|Autowrapping) and Primitive Wrapper
Table of Contents
1 - About
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
The wrapper classes for primitive types have generally the first letter as uppercase to differentiate them from the primitive one. For instance,
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.
2 - Articles Related
3 - Example
Ex with Java, the following class are the wrappers:
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: