Primitive Type Wrappers
As mentioned in Part I of this topic, Java uses primitive types, such as int and char, 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 the same instance of an int. 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, or wrap, the primitive types within a class. Thus, they are commonly referred
to as type wrappers. The type wrappers were introduced in Chapter 12. They are examined
in detail here.
The abstract class Number defines a superclass that is implemented by the classes that wrap
the numeric types byte, short, int, long, float, and double. Number has abstract methods
that return the value of the object in each of the different number formats. For example,
doubleValue( ) returns the value as a double, floatValue( ) returns the value as a float, 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.
Number has six concrete subclasses that hold explicit values of each numeric type: Double,
Float, Byte, Short, Integer, and Long.
Double and Float
Double and Float are wrappers for floating-point values of type double and float, respectively.
The constructors for Float are shown here:
Float(double num)
Float(float num)
Float(String str) throws NumberFormatException
As you can see, Float objects can be constructed with values of type float or double. They
can also be constructed from the string representation of a floating-point number.
The constructors for Double are shown here:
Double(double num)
Double(String str) throws NumberFormatException
Double objects can be constructed with a double value or a string containing a floating-
point value.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks