Witscale Test Center

13.5 The wrapper classes


13.5 The wrapper classes

The primitives in Java are not objects. However, sometimes you might want to treat them as objects instead of primitive values. For instance, if you want to store them in collections (Chapter 14), they must be objects. In such cases, you need to represent primitives as objects. The java.lang package provides a group of classes called the wrapper classes especially for this purpose. These classes can wrap (encapsulate) a single immutable primitive value. For example, a wrapper class Integer wraps an int value, a class named Boolean wraps a boolean value and so on. The names of the wrappers mostly correspond to the names of the primitives. However, they are not exactly same. Table 13.4 summarizes the primitives and their corresponding wrapper classes.

 

Table 13.4 Primitives and their corresponding wrapper classes.

 

Primitive types

Corresponding wrapper class in java.lang

boolean

Boolean

byte

Byte

short

Short

char

Character

int

Integer

long

Long

float

Float

double

Double

 

There is one more wrapper class Void that does not wrap any primitive type. Instead, it provides a placeholder class to hold a reference to the Class object representing the Java keyword void. This class has no functionality and cannot be even instantiated, as it does not have a public constructor.

 

The wrappers classes have another purpose besides wrapping the primitive values. They provide utility methods for primitives. Since the primitives are not considered as objects, you cannot invoke any methods on them. But the wrapper classes can define a lot of utility methods that does common conversion jobs. For instance, some of these methods are very useful for converting the primitives to String objects or converting a string object (representing a primitive value) to primitives. Before we see the details of the utility method, let us quickly see how to wrap a primitive value in an object.