Numeric Wrapper ClassesAs you saw in Lesson 7, Java supplies a corresponding wrapper class for each primitive type: Integer, Double, Float, Byte, Boolean, and so on. The primary use of the wrapper class is to convert primitives to object form so that they can be stored in collections. The wrapper classes for the numeric types have additional uses. You learned earlier in this lesson that each numeric wrapper class provides a MIN_VALUE and MAX_VALUE constant. You also saw how the Float and Double classes provide constants for Not a Number (NaN) and infinity. Printable RepresentationsThe class Integer provides static utility methods to produce printable representations of an int in hex, octal, and binary form.
The Java library includes general-purpose methods to produce a proper String for any radix (base). The following assertion shows how to get the trinary (base 3) String for an int.
Converting Strings to NumbersIn Lesson 8, you learned that the method Integer.parseInt takes a String and parses it to produce the corresponding int value. You typically use the parseInt method to convert user interface input into numeric form. All characters in the input String must be decimal digits, except for the first character, which may optionally be a negative sign. If the String does not contain a parseable integer, parseInt tHRows a NumberFormatException. An additional form of parseInt takes a radix, representing the base of the input string, as the second parameter. The method valueOf operates the same as parseInt, except that it returns a new Integer object instead of an int. Each of the corresponding numeric wrapper classes has a parsing method. For example, you may convert a String to a double using Double.parseDouble, or to a float using Float.parseFloat. The parseInt method can accept only decimal input. The decode method can parse an input string that might be in hex or octal, as these assertions show:
|
Saturday, October 31, 2009
Numeric Wrapper Classes
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment