Converting Strings to Wrapper Objects
Each wrapper class (except Character) defines the static method valueOf(String str) that returns the wrapper object corresponding to the primitive value represented by the String object passed as an argument ((2) in Figure 8.2). This method for the numeric wrapper types also throws a NumberFormatException if the String parameter is not a valid number.
static
WrapperType
valueOf(String str)
Boolean boolObj4 = Boolean.valueOf(“false”);
Integer intObj3 = Integer.valueOf(“1949”);
Double doubleObj2 = Double.valueOf(“3.14”);
Double doubleObj3 = Double.valueOf(“Infinity”);
In addition to the one-argument valueOf() method, the integer wrapper classes define an overloaded static valueOf() method that can take a second argument. This argument specifies the base (or radix) in which to interpret the string representing the signed integer in the first argument. Note that the string argument does not specify the prefix for the number system notation.
static
IntegerWrapperType
valueOf(String str, int base)
throws NumberFormatException
Byte byteObj1 = Byte.valueOf(“1010”, 2); // Decimal value 10
Short shortObj2 = Short.valueOf(“12”, 8); // Decimal value 10
Short shortObj3 = Short.valueOf(“012”, 8); // Decimal value 10
Short shortObj4 = Short.valueOf(“\012”, 8); // NumberFormatException
Integer intObj4 = Integer.valueOf(“-a”, 16); // Decimal value -10
Integer intObj6 = Integer.valueOf(“-0xa”, 16); // NumberFormatException
Long longObj2 = Long.valueOf(“-a”, 16); // Decimal value -10L
Converting Wrapper Objects to Strings
Each wrapper class overrides the toString() method from the Object class. The overriding method returns a String object containing the text representation of the primitive value in the wrapper object ((3) in Figure 8.2).
String toString()
String charStr = charObj1.toString(); // “\n”
String boolStr = boolObj2.toString(); // “true”
String intStr = intObj1.toString(); // “2020”
String doubleStr = doubleObj1.toString(); // “3.14”
Leave a Reply