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)
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.
How does that work?
It's a compiler-feature. The compiler will automatically generate the boxing-operation. What it'll actually do is to generate
Boolean.valueOf(true);
Because this way the existing (immutable) instances Boolean.TRUE and Boolean.FALSE will be used instead of creating a new one.
It's the same way that you can make String objects as such:
String s = "foobar"
It's just a perk in Java, really. I'm not sure why you would want to make your own wrapper class, either, considering that any primitive data type already has a predefined wrapper...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With