Nov 25, 2011

Wrappers For Basic Types

The classes Boolean, Character, Double, Float, Integer, and Long, defined in the package java.lang, are full-fledged Java objects whose purpose is to represent the values of primitive types. They all work in about the same way, so let's look at Boolean as an example.
You can use a boolean value to construct a Boolean object:
Boolean b = new Boolean( true );
To get boolean values back out of a Boolean object, use the booleanValue() method:
if ( b.booleanValue() ) System.out.println( "yes" );
The Boolean class also provides both constant Boolean values as class variables:
if ( b.equals( Boolean.TRUE ) )
  flag = Boolean.FALSE;
Similarly, each of the various wrapper classes provides class variables to delimit its range of legal values. The abstract class java.lang.Number is also provided as a superclass for the numerical classes Double, Float, Integer, and Long. The Number class merely specifies the four abstract methods intValue(), longValue(), floatValue(), and doubleValue(); this guarantees that any instance of a subclass of Number (say a Double) can be converted into any of the four representations (possibly with rounding). 


Post a Comment