Saturday 3 August 2013

14:Wrapper Classes, Selection Statements and Iteration Blocks

Learning Objectives
After completing this session, you will be able to:
‰  Implement wrapper classes
The Wrapper Classes
Some Facts:
‰  Primitive data types are not objects: Cannot access methods of the Object class
‰  Only actual objects can access methods of the Object class
‰  Need of wrapper classes: Need an object representation for the primitive type
variables to apply methods that are in-built in Java
Definition:Object representations of simple variables that are not object variables
‰  The designers decided instead that for each primitive type there would be a
corresponding wrapper class.
‰  An instance of a wrapper contains, or wraps, a primitive value of the corresponding
type.
‰  The wrappers are normal classes in the java.lang package that extend the Object
superclass like all Java classes.
‰  Other than for the primitive type int, the wrappers come with the same name as the
corresponding primitive type except that the first letter is capitalized:
oInteger is a wrapper class of the primitive int
oCharacter is a wrapper class of the primitive char
oDouble is a wrapper class of the primitive double
Wrapping a value:
Give the primitive to the wrapper constructor as shown in the following example:
Example:
int i = 123;
Integer iWrap = new Integer(i);
UnWrapping a value:
Each wrapper class has its own method for unwrapping a value.
For example, Boolean class has the method booleanValue(),
Character class has the method charValue() , and so on
Example: int unWrapped = iWrap.intValue();
Why Should You Use Wrapper Classes?
‰  Wrappers allow for situations where numerical values are needed but objects instead
of primitives are required.
‰  For example, a very useful tool is as the Vector class, which is a list that that can grow
or shrink, unlike an array.
‰  The elements of a Vector instance are object references.
‰  If one wants to use a Vector to hold a list of numbers, then the numbers must be
wrapped in instances of their corresponding type.
‰  The wrapper classes also provide various tools such as constants (the smallest and
largest possible int value, for example) and static methods.
‰  You will often use wrapper methods to convert a number type value to a string or a
string to a number type.
Converting Primitive Types to Objects (Wrapper) and the Reverse
The wrapper constructors create class objects from the primitive types. For example, for a double
floating point number "d" :
double d = 5.0;
Double aDouble = new Double(d);
Here a Double wrapper object is created by passing the double value in the Double constructor
argument.
In turn, each wrapper provides a method to return the primitive value like:
double r = aDouble.doubleValue();
Each wrapper has a similar method to access the primitive value:
‰  intValue()for Integer,
‰  booleanValue()for Boolean, and so forth
The following statement creates an instance of the Integer class with the integer value 7801.
Integer dataCount = new Integer(7801);
The following statement converts an Integer object to its primitive data type int. The result is an int
with value 7801.
int newCount = dataCount.intValue();
A common translation you need in programs is converting a String to a numeric type, such as an
int (Object->primitive).
String pennsylvania = "65000";
int penn = Integer.parseInt(pennsylvania);
Wrappers are Immutable
The two main applications of wrapper classes are:
‰  Wrapping a primitive so it can pretend to be an object.
‰  Applying the static utility methods (for example,Integer.parseInt()).
Once you create a wrapper object, there is no way to change the value of that object.
There is no setter method for a wrapper object.
Example:If you create a wrapper object like:
Integer iWrap = new Integer(25); then,
The value of iWrap will always be 25
You can, of course, refer iWrap to a different wrapper object, but then you will have two objects.
Try It Out
Problem Statement:
Write a program that illustrates the use of Boolean Wrapper class.
Code:
class BooleanWrapper {
public static void main(String args[]) {
boolean booleanVar = 1 > 2;
Boolean booleanObj = new Boolean("True");
/*
* primitive to object; can also use valueOf method
*/
Boolean booleanObj2 = new Boolean(booleanVar);
System.out.println("booleanVar = " + booleanVar);
System.out.println("booleanObj = " + booleanObj);
System.out.println("booleanObj2 = " + booleanObj2);
System.out.println("compare 2 wrapper objects: "
+ booleanObj.equals(booleanObj2));
/* object to primitive */
booleanVar = booleanObj.booleanValue();
System.out.println("booleanVar = " + booleanVar);
}
}
How It Works:
‰  When you run the program, it produces the following results:
booleanVar = false
booleanObj = true
booleanObj2 = false
compare 2 wrapper objects: false
booleanVar = true
Tips and Tricks:
What happens in Integer.parseInt() if the thing you pass is not a number? And does it recognize
spelled-out numbers like “three”?
Solution:
‰  Integer.parseInt() is used to get the int value of a String
‰  Integer.parseInt() works only on Strings thatrepresent the ASCII values for digits
(0,1,2,3,4,5,6,7,8,9). If you try to parse something like “two” or “real”, then the code will
throw an exception.
Summary
‰  The wrapper classes correlate to the primitive types.
‰  Wrappers have two main functions:
oTo wrap primitives so that they can be handled like objects.
oTo provide utility methods for primitives (usually conversions)
‰  The three most important methods available in the wrapper classes are:
oxxxValue() takes no argument, returns a primitive
oparseXxx() takes a String, returns a primitive, and throws
NumberFormatException
ovalueOf() takes a String, returns a wrapped object, throws
NumberFormatException
‰  Wrapper constructors can take a String or a primitive, except for Character, which can
only take a char.
Test Your Understanding
1.Which one of the following is wrong?
a)All the type wrappers are defined in java.lang package.
b)The isNaN() method is made available by the Double class.
c)A number cannot be converted to and from Strings.
d)The Runtime class encapsulates the java run time environment.
e)‘Like the String class, the wrapper classes are immutable’. Comment on this
statement.

No comments:

Post a Comment