Chapter 4. Autoboxing and Unboxing
Note
In this chapter:
When you begin to study Java, one of the first lessons is always about
objects. In fact, you could say that java.lang.Object is the very cornerstone
of Java. Practically 99% of everything you do in the language
revolves around that class, or one of its subclasses. It’s the 1% of the
time, though, that can be a pain—when you suddenly find yourself having
to convert between your objects and Java primitives.
Primitives in Java are your ints, shorts, chars, and so on—types that
aren’t objects at all. As a result,
Java has wrapper classes, such as
Integer, Short, and Character, which are object versions of the primitive
types. Where things get annoying is when you have to go back and
forth between the two—converting a primitive to its wrapper, using it,
then converting the object’s value back to a primitive. Suddenly, methods
such as intValue( ) begin to litter your code.
Happily, Tiger finally takes care of this issue, at least as much as can be expected without tossing out primitives completely. This is handled through two new conversion features: boxing and unboxing. And, just to add some more words to the English language, it does these conversions automatically, so we now talk about autoboxing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access