Recipe 5.3 Converting Numbers to Objects and Vice Versa


You need to convert numbers to objects and objects to numbers.


Use the Object Wrapper classes listed in Table 5-1 at the beginning of this chapter.


Often you have a primitive number and you need to pass it into a method where an Object is required. This frequently happens when using the Collection classes (see Chapter 7) in 1.4 and earlier (in 1.5 you can use AutoBoxing, described in Recipe 8.4).

To convert between an int and an Integer object, or vice versa, you can use the following:

// // int to Integer Integer i1 = new Integer(42); System.out.println(i1.toString( )); // or just i1 // Integer to int int i2 = i1.intValue( ); System.out.println(i2);

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: