How does the Java Boolean wrapper class get instantiated?

CrazyPenguin picture CrazyPenguin · Feb 3, 2011 · Viewed 8.1k times · Source

In java, I can write code like this

Boolean b = true ;

And it will work. I now have an object that holds the value "true".

How does that work? Why don't I have to pass the value through a constructor? Like so:

Boolean b = new Boolean( true ) ;

Also, can I make custom classes that I can instantiate in a similar way? If so what is that called?

So that I can do something like this:

Foobar foobar = "Test" ; 

And thus have my own wrapper class.

Thanks

Answer

OscarRyz picture OscarRyz · Feb 3, 2011

No you can't do the latter.

The former is called autoboxing and was introduced in Java v1.5 to auto wrap, primitives in their wrapper counterpart.

The benefit from autoboxing could be clearly been seen when using generics and/or collections:

From the article: J2SE 5.0 in a Nutshell

In the "Autoboxing and Auto-Unboxing of Primitive Types" sample we have:

Before (autoboxing was added)

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42)); 
int total = (list.get(0)).intValue();

After

 ArrayList<Integer> list = new ArrayList<Integer>();
 list.add(0, 42);
 int total = list.get(0);

As you see, the code is clearer.

Just bear in mind the last note on the documentation:

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.