Wrappers: Java’s Wrapper Classes for the Primitives Types Steve Bossie.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Taking Input Java Md. Eftakhairul Islam
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
The ArrayList Class and the enum Keyword
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Chapter 8: Arrays.
EXAMPLES (Arrays). Example Many engineering and scientific applications represent data as a 2-dimensional grid of values; say brightness of pixels in.
STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
Air Force Institute of Technology Electrical and Computer Engineering
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
 Base “primitive” types: TypeDescriptionSize intThe integer type, with range -2,147,483, ,147,483,647 4 bytes byteThe type describing a single.
Software Engineering Implementation Lecture 3 ASPI8-4 Anders P. Ravn, Feb 2004.
CS110 Programming Language I
Java Review Interface, Casting, Generics, Iterator.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
L EC. 02: D ATA T YPES AND O PERATORS (2/2) Fall Java Programming.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
Java Programming Strings Chapter 7.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
1 TP #4 n Last TP exercises solved; n Parsing command line arguments; n Static; n Wrapper classes for primitive types; n Package visibility.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Chapter 10 Object-Oriented Thinking. 2 Class Abstraction and Encapsulation Class abstraction means to separate class implementation details from the.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Arrays of Objects 1 Fall 2012 CS2302: Programming Principles.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Chapter 2 – Continued Basic Elements of Java. Chapter Objectives Type Conversion String Class Commonly Used String Methods Parsing Numeric Strings Commonly.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java Fundamentals 5. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Mixing integer and floating point numbers in an arithmetic operation.
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
1 Input/Output. 2 In Java input and output take place through I/O streams – An I/O stream represents an input source or output destination – Streams support.
Converting string to integer class StringToInt { public static void main (String arg[]) { // Assume arg[0] is the input string int result = 0, pos; int.
Wrapper Classes  Java offers a convenient way to incorporate, or wrap, a primitive data type into an object, for example, wrapping int into the class.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Object Oriented Programming Lecture 2: BallWorld.
Java Programming Language Lecture27- An Introduction.
Static Members and Methods
Exercise on Java Basics
Java Programming: From Problem Analysis to Program Design, 4e
CMSC 202 Static Methods.
Exercise on Java Basics
Unit-2 Objects and Classes
null, true, and false are also reserved.
Introduction to Java Programming
An Introduction to Java – Part I, language basics
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short.
An overview of Java, Data types and variables
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Chapter 2: Java Fundamentals
Java Programming Review 1
Chapter 10 Thinking in Objects Part 2
Presentation transcript:

Wrappers: Java’s Wrapper Classes for the Primitives Types Steve Bossie

Primitives & Wrappers Java has a wrapper class for each of the eight primitive data types: Primitive Type Wrapper Class Primitive Type Wrapper Class booleanBooleanfloatFloat byteByteintInteger charCharacterlongLong doubleDoubleshortShort

Use 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 a = new ArrayList (); 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( L); Long n1 = Long.valueOf( “ L ” );

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()); => 42 false

String => value The Wrapper class for each primitive type has a method parseType() to parse a string representation & return the literal value. Integer.parseInt(“42”)=> 42 Boolean.parseBoolean(“true”)=> true Double.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 = 0 arg # 1 = 42 arg # 2 = 999 arg # 3 = 0.0 arg # 4 = 1.42 arg # 5 =

Sample values: boolObj new Boolean(Boolean.TRUE); charObj = new Character('a'); byteObj = new Byte("100"); shortObj = new Short("32000"); intObj = new Integer( ); longObj = new Long( L); floatObj = new Float(1.42); doubleObj = new Double(1.42); printWrapperInfo(); //method to print objects above

Sample values (output from previous slide): => For Boolean & Character Wrappers: Boolean:true Character:a For Number wrappers: Byte:100 Short:32000 Integer: Long: Float:1.42 Double:1.42

Each 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: Long: Float: E38 Double: E308

Many 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

Bloch’s counting program: Java 1.4 Version public 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 m = new TreeMap (); 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 code.