NJIT CS 602 - Java’s Wrapper Classes for the Primitives Types

Unformatted text preview:

Wrappers: Java’s Wrapper Classes for the Primitives TypesPrimitives & WrappersUse of the Wrapper ClassesValue => Object: Wrapper Object CreationObject => ValueString => valueParsing argument listsSlide 8Sample values:Sample values (output from previous slide):Each Number Wrapper has a MAX_VALUE constant:MAX values (output from previous slide):Many useful utility methods, e.g., for Integer:Double & Float: Utilities for Arithmetic Operations:Primitive - Wrapper Split Personality:Bloch’s counting program: Java 1.4 VersionNotes on the 1.4 Version:Bloch’s counting program: Java 1.5 Version:Notes on the 1.5 Version:Final NotesWrappers:Java’s Wrapper Classes for the Primitives TypesSteve BossiePrimitives & Wrappers•Java has a wrapper class for each of the eight primitive data types:Primitive TypeWrapper ClassPrimitive TypeWrapper Classboolean Boolean float Floatbyte Byte int Integerchar Character long Longdouble Double short ShortUse of the Wrapper Classes•Java’s 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:List<Integer> a = new ArrayList<Integer>();methodRequiringListOfIntegers(a);Value => Object: Wrapper Object Creation•Wrapper.valueOf() takes a value (or string) and returns an object of that class:Integer i1 = Integer.valueOf(42);Integer i2 = Integer.valueOf(“42”);Boolean b1 = Boolean .valueOf(true);Boolean b2 = Boolean .valueOf(“true”);Long n1 = Long.valueOf(42000000L);Long n1 = Long.valueOf(“42000000L”);Object => Value•Each wrapper class Type has a method typeValue to obtain the object’s value:Integer i1 = Integer.valueOf(42);Boolean b1 = Boolean.valueOf(“false”);System.out.println(i1.intValue());System.out.println(b1.intValue());=>42falseString => value•The Wrapper class for each primitive type has a method parseType() to parse a string representation & return the literal value.Integer.parseInt(“42”) => 42Boolean.parseBoolean(“true”) => trueDouble.parseDouble(“2.71”) => 2.71//…•Common use: Parsing the arguments to a program:Parsing argument lists// Parse int and float program args.public parseArgs(String[] args) { for (int i = 0; i < args.length; i++) { try { …println(Integer.parseInt(args[i])); } catch (Exception e) { try { …println(Float.parseFloat(args[i])); } finally { } }}}Parsing argument lists=>arg # 0 = 0arg # 1 = 42arg # 2 = 999arg # 3 = 0.0arg # 4 = 1.42arg # 5 = 9.0008Sample 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 aboveSample values (output from previous slide):=> For Boolean & Character Wrappers: Boolean:true Character:a For Number wrappers: Byte:100 Short:32000 Integer:2000000 Long:500000000000000000 Float:1.42 Double:1.42Each Number Wrapper has a MAX_VALUE constant:byteObj = new Byte(Byte.MAX_VALUE);shortObj = new Short(Short.MAX_VALUE);intObj = new Integer(Integer.MAX_VALUE);longObj = new Long(Long.MAX_VALUE);floatObj = new Float(Float.MAX_VALUE);doubleObj = new Double(Double.MAX_VALUE);printNumValues("MAXIMUM NUMBER VALUES:");MAX values (output from previous slide):=> Byte:127 Short:32767 Integer:2147483647 Long:9223372036854775807 Float:3.4028235E38 Double:1.7976931348623157E308Many useful utility methods, e.g., for Integer: int hashCode()static int numberOfLeadingZeros(int i)static int numberOfTrailingZeros(int i)static int reverse(int i)static int reverseBytes(int i)static int rotateLeft(int i, int distance)static int rotateRight(int i, int distance)static String toBinaryString(int i)static String toHexString(int i)static String toOctalString(int i)static String toString(int i, int radix)Double & Float: Utilities for Arithmetic Operations:•Constants POSITIVE_INFINITY & NEGATIVE_INFINITY•Constant NaN = Not-a-Number (NaN) value.•Methods isNaN(), isInfinite()Primitive - Wrapper Split Personality:•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. Bloch’s article can be found at http://java.sun.com/features/2003/05/bloch_qa.htmlBloch’s counting program: Java 1.4 Versionpublic class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { // Maps word (String) to frequency (Integer) Map m = new TreeMap(); for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m); }}Notes on the 1.4 Version:•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:Bloch’s counting program: Java 1.5 Version:•Bloch’s 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); }}Notes on the 1.5 Version:•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.Final Notes•Java’s 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.5’s generics, autoboxing and the enhanced for loop to avoid unclear


View Full Document

NJIT CS 602 - Java’s Wrapper Classes for the Primitives Types

Download Java’s Wrapper Classes for the Primitives Types
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java’s Wrapper Classes for the Primitives Types and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java’s Wrapper Classes for the Primitives Types 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?