Autoboxing and Unboxing 1

Autoboxing, introduced in Java 5, is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, double and Double, etc). The underlying code that is generated is the same, but autoboxing provides a sugar coating that avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types.    

 
Java 5 also supports automatic unboxing, where wrapper types are automatically converted into their primitive equivalents if needed for assignments or method or constructor invocations.
 
For example
int i = 0;
i = new Integer(5);  // auto-unboxing
Integer i2 = 5;          // autoboxing
 
Prefer primitive types
Use the primitive types where there is no need for objects for following reasons.
  1. Primitive types may be a lot faster than the corresponding wrapper types, and are never slower.
  2. The immutability (can’t be changed after creation) of the wrapper types may make it their use impossible.
  3. There can be some unexepected behavior involving == (compare references) and .equals() (compare values).
Rate this post

One comment on “Autoboxing and Unboxing

  1. Reply lishou Jul 20,2013 12:58 pm

    In fact programming is nothing however it a logic, if you get handle on it afterward you are the professional else nil.

Leave a Reply