The parse() MethodsWe've talked about the need to convert a String representation of a primitive value into a primitive value. There are two general ways to do this. The first way involves a combination of the valueOf() and <primitive >Value() methods previously described. As an example, consider the following syntax ” double width = Double.valueOf("4.3").doubleValue(); The above statement calls the static method valueOf() of the Double class. This method parses the String " 4.3 " and creates a Double object that wraps the value 4.3. The doubleValue() method is called on this object and returns the primitive double value 4.3 . This value is assigned to the double variable named width . Table 15.5. String Parsing Methods
Converting a String to a primitive value in this manner is a little convoluted. You must create an intermediate wrapper class object that you don't use for any other purpose. The second way to convert a String representation of a primitive value into a primitive value is easier. Some of the primitive variable wrapper classes define parse() methods that convert a String directly into a primitive value. A list of the parse() methods for each wrapper class is shown in Table 15.5. You can see from Table 15.5 that all of the parse() methods take a String argument to represent the number to be parsed. The methods defined in each class will only return the primitive type wrapped by the class. These methods can all throw a NumberFormatException if the argument passed to the method is not a parsable String . Example: Using String Parsing MethodsTo see the parse() methods in action, look at the "Parsing an Input File" example at the end of this chapter. |