[an error occurred while processing this directive]
Domain for sale!
Start Search Contents Index Links About

Boxing / Unboxing

Automatic type conversion

2005 - Week 38 - Havard Rast Blok

The Java 5.0, or JDK 1.5 if you like, made several updates to the Java language, one of which was the boxing and unboxing mechanism. Simply put, it converts or casts between primitive types and the wrapper classes without explicit code on your part.

In an old style code, you would have the manually wrap primitive types in wrapper classes to add them to Collections etc., like the code below.

Vector v;
...
v.add( new Integer(111) );
...
int tmp = ((Integer)v.get(i)).intValue();
The class below implements this example.


NoBoxing.java

The new way of handling this, using boxing and unboxing, save both some code and potential errors. Note how integer values are added right into the Vector, and how no the intValue() method is no longer needed.

v.add( 111 );
...
int tmp = (Integer)v.get(i);
The cast from the Object returned from the get() method is still required since the Vector used is unchecked. That is, no generics is used to specify the type of elements.


BoxingTest.java

The previous examples used boxing and unboxing of integer, but of course all the Java primitive types are supported. The final example show boxing of all types in the save Vector. The output should be like this:

Class: java.lang.Integer, value=111
Class: java.lang.Float, value=2.2
Class: java.lang.Double, value=3.3
Class: java.lang.Short, value=4
Class: java.lang.Long, value=50
Class: java.lang.Byte, value=6
Class: java.lang.Character, value=a
Class: java.lang.Boolean, value=true


AllBoxingTest.java

It should be noted that this is an example, and that this type of code is hardly recommended. For for on checked Collections, come back to this site soon.



site: Håvard Rast Blok
mail:
updated: 16 July 2010