Java Reference
In-Depth Information
Type Wrappers
As you know, Java uses primitive types, such as
int
or
double
, to hold the basic data types
supported by the language. Primitive types, rather than objects, are used for these quantities
for the sake of performance. Using objects for these basic types would add an unacceptable
overhead to even the simplest of calculations. Thus, the primitive types are not part of the
object hierarchy, and they do not inherit
Object
.
Despite the performance benefit offered by the primitive types, there are times when you
will need an object representation. For example, you can't pass a primitive type by refer-
ence to a method. Also, many of the standard data structures implemented by Java operate
on objects, which means that you can't use these data structures to store primitive types.
To handle these (and other) situations, Java provides
type wrappers
, which are classes that
encapsulate a primitive type within an object. The type wrapper classes were introduced
briefly in
Chapter 10
.
Here, we will look at them more closely.
The type wrappers are
Double
,
Float
,
Long
,
Integer
,
Short
,
Byte
,
Character
, and
Boolean
, which are packaged in
java.lang
. These classes offer a wide array of methods
that allow you to fully integrate the primitive types into Java's object hierarchy.
Probably the most commonly used type wrappers are those that represent numeric val-
ues. These are
Byte
,
Short
,
Integer
,
Long
,
Float
, and
Double
. All of the numeric type
wrappers inherit the abstract class
Number
.
Number
declares methods that return the
value of an object in each of the different numeric types. These methods are shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
For example,
doubleValue( )
returns the value of an object as a
double
,
floatValue( )
re-
turns the value as a
float
, and so on. These methods are implemented by each of the nu-
meric type wrappers.
All of the numeric type wrappers define constructors that allow an object to be construc-
ted from a given value, or a string representation of that value. For example, here are the
constructors defined for
Integer
and
Double
: