Professional Documents
Culture Documents
Steve Bossie
NJIT
1
3/24/200804/29/06
Java has a wrapper class for each of the eight primitive data types:
Primitive Type boolean byte char double Wrapper Class Boolean Byte Character Double
3/24/2008
Javas primitive data types (boolean, int, etc.) are not classes. Wrapper classes are used in situations where objects are required, such as for elements of a Collection:
3/24/2008
Wrapper.valueOf() takes a value (or string) and returns an object of that class:
3/24/2008
Each wrapper class Type has a method typeValue to obtain the objects value:
The Wrapper class for each primitive type has a method parseType() to parse a string representation & return the literal value.
=> 42 => true => 2.71
arg # 3 = 0.0
arg # 4 = 1.42 8
3/24/2008
Sample values:
boolObj new Boolean(Boolean.TRUE); charObj = new Character('a'); byteObj = new Byte("100"); shortObj = new Short("32000"); intObj = new Integer(2000000); longObj = new Long(500000000000000000L); floatObj = new Float(1.42); doubleObj = new Double(1.42);
printWrapperInfo(); //method to print objects above
3/24/2008
10
3/24/2008
11
3/24/2008
12
3/24/2008
14
3/24/2008
Although the Wrapper classes provide needed functionality (OO versions of primitives and supporting functionality), Java code is sometimes overly complicated due to the necessary conversions between the primitive and wrapper versions of data being manipulated. Joshua Bloch published a technical note, excerpts of which are used below. Blochs article can be found at http://java.sun.com/features/2003/05/bloch_qa.html
3/24/2008
15
16
3/24/2008
This program generates a frequency table of words on the command line. It uses a Map whose keys are the words and whose values are the number of times that each word occurs on the line. The inner-loop code is a bit convoluted. Bloch continues by writing the same program with autoboxing, generics, and an enhanced for loop:
17
3/24/2008
Blochs implementation rewritten with autoboxing, generics, and an enhanced for loop:
public class Freq { public static void main(String args[]) { Map<String, Integer> m = new TreeMap<String, Integer>(); for (String word : args) { Integer freq = m.get(word); m.put(word, (freq == null ? 1 : freq + 1)); } System.out.println(m); } }
18
3/24/2008
This version is much clearer, and is a good example of the use of a Wrapper class without the pitfalls of convoluted primitive-wrapper conversions.
19
3/24/2008
Final Notes
Javas wrapper classes are useful and provide a great deal of functionality, well beyond that of the primitive types. Code using Wrapper classes and primitives can be convoluted. Use Java 1.5s generics, autoboxing and the enhanced for loop to avoid unclear code.
20
3/24/2008