Converting a Wrapper Class Object to a Primitive Value


The primitive variable wrapper classes are used to wrap a class around a primitive value, but sometimes you need to access the primitive value that was wrapped. Every primitive variable wrapper class defines methods to convert an instance of itself back into a primitive data type value. These methods are shown in Table 15.4.

The numerical wrapper classes Byte , Double , Float , Integer , Long , and Short define a common set of methods. They can be used to convert the primitive value represented by the object into any numerical primitive type. In effect these methods allow you to cast the value contained by a numerical wrapper class object.

Table 15.4. Primitive Variable Conversion Methods

C LASS

M ETHOD

Byte, Double, Float, Integer, Long, Short

public byte byteValue()

public double doubleValue()

public float floatValue()

public int intValue()

public long longValue()

public short shortValue()

Boolean

public boolean booleanValue()

Character

public char charValue()

The Boolean and Character classes are a bit more exclusive. The Boolean class only defines the booleanValue() method for extracting the boolean value wrapped by the class. Similarly, the Character class only defines the charValue() method to return the char value wrapped by the class.

Example: Extracting Primitive Values from Wrapper Class Objects

Look at the "Using Primitive Variable Wrapper Classes" example in the previous section where the doubleValue() method is used to retrieve the primitive double value associated with a Double object.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net