The parse() Methods


The parse() Methods

We'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

C LASS

M ETHOD

Byte

public static byte parseByte(String value)

public static byte parseByte(String value, int radix)

Double

public static double parseDouble(String value)

Float

public static float parseFloat(String value)

Integer

public static int parseInt(String value)

public static int parseInt(String value, int radix)

Long

public static long parseLong(String value)

public static long parseLong(String value, int radix)

Short

public static short parseShort(String value)

public static short parseShort(String value, int radix)

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 Methods

To see the parse() methods in action, look at the "Parsing an Input File" example at the end of this chapter.



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