THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The efficiency and convenience of using an int can be maintained, while an object can still be obtained
when necessarythe best of both worlds.


A second purpose of the wrapper classes is to provide a home for methods and variables related to the type
(such as string conversions and value range constants). Here, for example, is how you might check whether
you could use a faster float calculation on a particular value or whether the value requires a larger range
than a float provides and so must be performed as a double calculation:


double aval = Math.abs(value);
if (Float.MAX_VALUE >= aval && aval >= Float.MIN_VALUE)
return fasterFloatCalc((float) value);
else
return slowerDoubleCalc(value);


The following sections cover methods and constants specific to each particular wrapper class, but first let's
look at some things that are common to most of the wrapper classes.


8.1. Common Fields and Methods


Except where individually noted, the following sections define constructors, constants, and methods that are
defined for each of the wrapper classes. The general exception is the Void class which supports almost
nothingsee page 187.


For the constructors and methods that convert strings into values, each class defines the valid form that the
string can take, and these are described in the section for each class. For the numeric types, an invalid string
format results in NumberFormatException being thrown.


The term radix, used in several places in the wrapper classes, is another word for numeric base. For example,
decoding a long in radix 8 means the same as decoding it in base 8. The allowable range for a radix is 2
through 36.


In the following, Type refers to the wrapper class, and type is the corresponding primitive type.


8.1.1. Construction


Each wrapper class defines an immutable object for the primitive value that it is wrapping. This means that
once a wrapper object has been created, the value represented by that object can never be changed. So, for
example, the object created by newInteger(1) will always have the value 1, and no methods of class
Integer allow you to modify this value.


Each wrapper class has the following constructors:


A constructor that takes a value of the primitive type and creates an object of the corresponding
wrapper class. The constructors Character(char) and Integer(int) are examples.


A constructor that converts a single String parameter into the object's initial value (except
Character, which has no such constructor)for example, newFloat("6.02e23").


Each wrapper class, Type, also has the following methods:


public staticTypevalueOf(typet)
Free download pdf