Ask Questions?

View Latest Questions

Advertisement


 
 

Autoboxing
Posted on: July 26, 2006 at 12:00 AM
Autoboxing, introduced in Java 5, is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes

Java Notes

Autoboxing

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.

Example

With AutoboxingWithout Autoboxing
int i;
Integer j;
i = 1;
j = 2;
i = j;
j = i;
int i;
Integer j;
i = 1;
j = new Integer(2);
i = j.valueOf();
j = new Integer(i);

Prefer primitive types

Use the primitive types where there is no need for objects for two 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). See the reference below for examples.

References

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com