Java Reference
In-Depth Information
As we've discussed previously, Java represents data by using primitive types (such
as
int
,
double
,
char
, and
boolean
) in addition to classes and objects. Having two
categories of data to manage (primitive values and object references) can present
a challenge in some circumstances. For example, we might create an object that
serves as a container to hold various types of other objects. However, in a specific
situation, we may want it to hold a simple integer value. In these cases we need
to “wrap” a primitive value into an object.
A
wrapper class
represents a particular primitive type. For instance, the
Integer
class represents a simple integer value. An object created from the
Integer
class stores a single
int
value. The constructors of the wrapper classes
accept the primitive value to store. For example:
Integer ageObj =
new
Integer(40);
Once this declaration and instantiation are performed, the
ageObj
object effectively represents the integer 40 as an object. It can be used
wherever an object is needed in a program rather than a primitive
type.
For each primitive type in Java there exists a corresponding wrapper class in
the Java class library. All wrapper classes are defined in the
java.lang
package.
Figure 3.8 shows the wrapper class that corresponds to each primitive type.
Note that there is even a wrapper class that represents the type
void
. However,
unlike the other wrapper classes, the
Void
class cannot be instantiated. It simply
represents the concept of a void reference.
KEY CONCEPT
A wrapper class allows a primitive
value to be managed as an object.
Primitive Type
Wrapper Class
byte
short
int
long
float
double
char
boolean
void
Byte
Short
Integer
Long
Float
Double
Character
Boolean
Void
FIGURE 3.8
Wrapper classes in the Java class library
Search WWH ::
Custom Search