4.1 Converting Primitives to Wrapper Types
Literal values in Java are always
primitives. The number 0, for example,
is an int, and must be converted to an object through code like this:
Integer i = new Integer(0);
This is pretty silly, for obvious reasons, and Tiger removes the need for
such nonsense through boxing.
4.1.1 How do I do that?
You can now dispense with the manual conversions, and let the Java virtual
machine (VM) handle conversion of primitives to object wrapper
types:
Integer i = 0;
In the background, Java handles taking this primitive and turning it into
a wrapper type. The same conversion happens with explicit primitive
types:
int foo = 0;Integer integer = foo;
If you're not completely convinced of the value of this, try typing these
statements into a pre-Tiger compiler, and watch in amazement as you
get some rather ridiculous errors:NOTEThe "compile-1.4"
target compiles
the examples
from this chapter
with the "-source
1.4" switch.
These errors "magically" disappear in Tiger when using the - source 1.5
compile-1.4:
[echo] Compiling all Java files...
[javac] Compiling 1 source file to classes
[javac] src\com\oreilly\tiger\ch04\ConversionTester.java:6: incompatible
types
[javac] found : int
[javac] required: java.lang.Integer
[javac] Integer i = 0;
[javac] ^
[javac] src\com\oreilly\tiger\ch04\ConversionTester.java:9: incompatible
types
[javac] found : int
[javac] required: java.lang.Integer
[javac] Integer integer = foo;
[javac] ^
[javac] 2 errors
switch.
4.1.2 What just happened?
Behind the scenes, these
primitive values are boxed. Boxing refers to the
conversion from a primitive to its corresponding wrapper type: Boolean,
Byte, Short, Character, Integer, Long, Float, or Double. Because this
happens automatically, it's generally referred to as autoboxing.It's also common for Java to perform a widening conversion in addition to
boxing a value:
Number n = 0.0f;
Here, the literal is boxed into a Float, and then widened into a Number.NOTEIt's possible to
specifically
request a boxing
conversionthat's
basically a new
form of casting.
It's just easier to
let the VM
handle it, though.Additionally, the Java specification indicates that certain primitives are
always to be boxed into the same immutable wrapper objects. These
objects are then cached and reused, with the expectation that these are
commonly used objects. These special values are the boolean values true
and false, all byte values, short and int values between -128 and 127,
and any char in the range \u0000 to \u007F. As this all happens behind
the scenes, it's more of an implementation detail than something you
need to worry much about.