Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Primitive Type Wrappers


As mentioned in Part I of this book, Java uses primitive types, such asintandchar, for
performance reasons. These data types are not part of the object hierarchy. They are passed
by value to methods and cannot be directly passed by reference. Also, there is no way for
two methods to refer to thesame instanceof anint. At times, you will need to create an
object representation for one of these primitive types. For example, there are collection
classes discussed in Chapter 17 that deal only with objects; to store a primitive type in one
of these classes, you need to wrap the primitive type in a class. To address this need, Java
provides classes that correspond to each of the primitive types. In essence, these classes
encapsulate, orwrap,the primitive types within a class. Thus, they are commonly referred
to astype wrappers.The type wrappers were introduced in Chapter 12. They are examined
in detail here.

Number


The abstract classNumberdefines a superclass that is implemented by the classes that wrap
the numeric typesbyte,short,int,long,float, anddouble.Numberhas abstract methods
that return the value of the object in each of the different number formats. For example,
doubleValue( )returns the value as adouble,floatValue( )returns the value as afloat, and
so on. These methods are shown here:

byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )

The values returned by these methods can be rounded.
Numberhas six concrete subclasses that hold explicit values of each numeric type:Double,
Float,Byte,Short,Integer, andLong.

Double and Float


DoubleandFloatare wrappers for floating-point values of typedoubleandfloat, respectively.
The constructors forFloatare shown here:

Float(doublenum)
Float(floatnum)
Float(Stringstr) throws NumberFormatException

As you can see,Floatobjects can be constructed with values of typefloatordouble. They
can also be constructed from the string representation of a floating-point number.
The constructors forDoubleare shown here:

Double(doublenum)
Double(Stringstr) throws NumberFormatException

Doubleobjects can be constructed with adoublevalue or a string containing a floating-
point value.

386 Part II: The Java Library

Free download pdf