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
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)
After
As you see, the code is clearer.
Just bear in mind the last note on the documentation: