Witscale Test Center

13.5 The wrapper classes > 13.5.4 How to get the primitive values from string objects?


13.5.4 How to get the primitive values from string objects?

The six numeric wrapper classes have a static method parseXxx() for the corresponding primitive type. It takes a string as an argument and returns a primitive value. The four wrapper classes for integral type (Byte, Short, Integer and Long) have a overloaded version of this method to take radix (to indicate the number system) as second argument. For example, the Wrapper class Integer has two parsetInt() methods with following signatures: -

 

public static int parseInt(String s) throws NumberFormatException

public static int parseInt(String s, int radix)throws NumberFormatException

 

But the Float class has only one parseXxx() method. The signature is:

 

public static float parseFloat(String s) throws NumberFormatException

 

The Xxx in the parseXxx() denote the corresponding primitive type for the given wrapper class. For example, in the Short class, parseXxx() means the parseShort() method. This convention is used in the SCJP objective to talk about parse methods.

 

In parseXxx() methods, nowhere an instance of a wrapper class comes into picture. These methods are defined as static methods and act as pure utility methods provided by the Wrapper class. You can use one of these methods to get a primitive values from a string object as:

 

int i = Integer.parseInt("5");         // 5 is assifned to i

int n = Integer.parseInt("FF",16);           // 255 is assifned to n

float f = Float.parseFloat("2.73");    // 2.73df is assigned to f

 

These methods also throw a runtime exception NumberFormatException if the string cannot be parsed into a corresponding primitive value. For example, following code will throw exception at runtime.

 

long longVal = Long.parseLong("someString"); // throws runtime exception

 

The string “someString” does not represent a long value. Hence, it cannot be parsed.  Even if the string represents a value, the runtime exception may occur. For example,

 

byte byteVal = Byte.parseByte("FF",16); // throws runtime exception

 

The string “FF” is equivalent to decimal value 256, which is out of range for byte. Hence it cannot be parsed to a byte value.

 

The parseXxx() methods are similar to the valueOf() methods as both are static methods that accepts String as argument. But parseXxx() returns primitive value whereas the valueOf() returns a wrapper object. Also the parseXxx() methods are present only in the numeric wrapper classes, but the valueOf() methods are present all wrapper classes (including Boolean and Character).