Converting Primitive Values to Strings

Each wrapper class defines a static method toString(type v) that returns the string corresponding to the primitive value of type, which is passed as an argument ((6a) in Figure 8.2).

Click here to view code image

static String toString(
type
 v)

Click here to view code image

String charStr2   = Character.toString(‘\n’);  // “\n”
String boolStr2   = Boolean.toString(true);    // “true”
String intStr2    = Integer.toString(2020);    // “2020”
String doubleStr2 = Double.toString(3.14);     // “3.14”

For integer primitive types, the base is assumed to be 10. For floating-point numbers, the text representation (decimal form or scientific notation) depends on the sign and the magnitude (absolute value) of the number. The NaN value, positive infinity, and negative infinity will result in the strings “NaN”, “Infinity”, and “-Infinity”, respectively.

In addition, the wrapper classes Integer and Long define methods for converting integers to text representations in decimal, binary, octal, and hexadecimal notation (p. 435).

Converting Wrapper Objects to Primitive Values

Unboxing is a convenient way to unwrap the primitive value in a wrapper object ((4a) in Figure 8.2 and §2.3, p. 45).

Click here to view code image

char    c = charObj1;                       // ‘\n’
boolean b = boolObj2;                       // true
int     i = intObj1;                        // 2020
double  d = doubleObj1;                     // 3.14

Each wrapper class defines a type Value() method that returns the primitive value in the wrapper object ((4b) in Figure 8.2).

type type
Value()

Click here to view code image

char    c = charObj1.charValue();           // ‘\n’
boolean b = boolObj2.booleanValue();        // true
int     i = intObj1.intValue();             // 2020
double  d = doubleObj1.doubleValue();       // 3.14

In addition, each numeric wrapper class defines type Value() methods for converting the wrapper object to a value of any numeric primitive data type. These methods are discussed later.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *