Java Reference
In-Depth Information
pure object‐oriented programming language. However, Java 5 introduced a concept called
auto-
boxing
, where programmers can access primitive types as if they were instances of their wrap-
per class.
autoBoxing
Autoboxing is an automatic conversion made by the Java compiler between primi-
tive types and their corresponding wrapper classes. For example, converting a
double
to a
Double
is called boxing, and converting a
Double
back to a
double
is
called unboxing.
For each primitive type, there is an associated wrapper class available:
➤
boolean
wrapper class:
Boolean
➤
byte
wrapper class:
Byte
➤
char
wrapper class:
Character
➤
float
wrapper class:
Float
➤
int
wrapper class:
Integer
➤
long
wrapper class:
Long
➤
short
wrapper class:
Short
➤
double
wrapper class:
Double
➤
void
wrapper class:
Void
The
void
wrapper class does not actually hold a value but is a representation for
the
void
return type.
The mechanism of autoboxing entails that it is perfectly fine to write code like this:
Double d1 = 5.4;
double d2 = new Double(3.3);
You might be wondering if it makes sense to use the primitive types' wrapper
classes instead of the default keywords. The best practice, however, is simply to
use the primitive keywords and the wrapper classes only when you need to, that
is, when you want to access a primitive variable as an object. Later in this chapter,
when you read about Java's collection types, you will see a typical use case where
this is necessary.
In Chapter 2, you read an overview on Java's language structure, including the syntax for classes,
methods, and variables, and the different types in Java. Don't worry if you don't recall all the
details, as you will revisit these concepts again in the following sections and learn about them
step‐by‐step.
Search WWH ::
Custom Search