Saturday, October 31, 2009

Numeric Wrapper Classes








Numeric Wrapper Classes


As 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 Representations


The class Integer provides static utility methods to produce printable representations of an int in hex, octal, and binary form.



assertEquals("101", Integer.toBinaryString(5));
assertEquals("32", Integer.toHexString(50));
assertEquals("21", Integer.toOctalString(17));


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.



assertEquals("1022", Integer.toString(35, 3));


Converting Strings to Numbers


In 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:



assertEquals(253, Integer.decode("0xFD"));
assertEquals(253, Integer.decode("0XFD"));
assertEquals(253, Integer.decode("#FD"));
assertEquals(15, Integer.decode("017"));
assertEquals(10, Integer.decode("10"));
assertEquals(-253, Integer.decode("-0xFD"));
assertEquals(-253, Integer.decode("-0XFD"));
assertEquals(-253, Integer.decode("-#FD"));
assertEquals(-15, Integer.decode("-017"));
assertEquals(-10, Integer.decode("-10"));








    No comments: