Saturday 3 August 2013

15:Auto boxing unboxing

Learning Objectives
After completing this session, you will be able to:
‰  Identify Wrapper classes for the primitive data types
‰  Describe Auto boxing
‰  Explain unboxing
Primitive Types: Wrapper Classes
The following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean java.lang.Boolean
byte  java.lang.Byte
char  java.lang.Character
double java.lang.Double
float  java.lang.Float
int  java.lang.Integer
long  java.lang.Long
short  java.lang.Short
void  java.lang.Void
Converting Strings to Primitive Types
The primitive type wrappers provide various static utility methods such as those to convert
numbers to strings and strings to numbers.
You occasionally want to pass values to an applet. The applet hypertext tag includes the param
sub-tag for this like the following:
<applet ...>
<param name = "string_name" value = "string_value" >
</applet>
for passing strings to the applet program. The parameter has a name and corresponding value.
For example, you could pass two strings with numbers like the following:
<applet code="myApplet" codebase="Java" width=100 height=50>
<param name="fpNumber" value="12.45">
<param name="intNumber" value="10">
</applet>
In the applet code, usually in the init() method, you then use the getParameter(String) method from
the applet class to obtain a given parameter, as in the following code:
String fpStr = getParameter ("fpNumber");
String intStr = getParameter ("intNumber");
You now have the parameter values in string form and need to convert them to numbers. The
wrapper classes provide tools for thisin the form of static methods.
For example, the following code:
public void init () {
string fpStr= getParameter ("fpNumber");
double fpNum = Double.parseDouble (fpStr);
String intStr = getParameter ("intNumber");
int intNum = Integer.parseInt (intStr);
……
shows the use of the parseDouble method in Double and the parseInt method in Integer.
Converting Primitive Types to Strings
‰  You can convert a primitive type to a string in several ways.
‰  The String class provides the static valueOf methods (there is one for each primitive
type).
‰  The easiest way to turn a number into a string is to simply concatenate using the "+"
operator:
‰  The “+” operator is overloaded in Java (in fact, it is the only overloaded operator) as a
string concatenator.
‰  Anything added to a string is also a string.
Converting Primitive Types to Strings (Example)
In the following code, you convert numerical values to strings using the valueOf() methods (there is
one for each primitive type) of String class:
int i = 1;
double d = 5.0;
String dStr = String.valueOf(d);
String iStr = String.valueOf(i);
In the following code, you convert numericalvalues to strings using the "+" operator:
String aStr = "d = " + d;
String bStr = "i = " + i;
Now dStr and iStr objects hold string representations of 5.0 and 1, while aStr holds "d = 5.0" and
bStr holds "i = 1“.
Autoboxing
‰  The autoboxing feature added to Java 5.0 does the conversion (wrapping) from
primitive to wrapper object.
‰  This "wrapping" is called "autoboxing" inthe sense that the primitive value is
automatically "boxed up" into the wrapper object.
‰  Autoboxing is available for all the primitive or wrapper types.
Without Autoboxing (Java versions before 5.0)
Example:An ArrayList of primitive ints
public void doNumsOldWay() {
ArrayList listOfNumbers = new ArrayList
listOfNumbers.add(new Integer(3));
Integer one = (Integer) listOfNumbers.get(0);
int intOne = one.intValue();
}
With Autoboxing (Java versions 5.0 or greater)
Example:An ArrayList of primitive ints
public void doNumsNewWay() {
ArrayList<Integer> listOfNumbers = new ArrayList<Integer>;
listOfNumbers.add(3);
int num = listOfNumbers.get(0);
}
Autoboxing Illustrations
The general rule is that boxing and unboxing work wherever you can normallyuse a primitive or a
wrapped object.
It can be illustrated in the following:
‰  Method arguments
‰  Return values
‰  Boolean expressions
‰  Operations on numbers
‰  Assignments
Method Arguments
‰  If a method takes a wrapper type, then you can pass a reference to a wrapper or a
primitive of the matching type.
‰  If a method takes a primitive, then you can pass in either a compatible primitive or a
reference to a wrapper of that primitive type.
‰  Example: void takeNumber(Integer i) { }
Return Values
‰  If a method declares a primitive return type, then you can return either a compatible
primitive or a reference to the wrapper of that primitive type.
‰  If a method declares a wrapper return type, then you can return either a reference to
the wrapper type or a primitive of the matching type.
‰  Example:
int giveNumber() {
return x;
}
‰  In the preceding example, x can be either a reference to Integer wrapper or int
primitive type.
Boolean Expressions
Any place a boolean value is expected, you can use either an expression that evaluates to a
boolean (4 > 2), or a primitive boolean, or a reference to a Boolean wrapper.
Example:
boolean one = true; // nothing new here
Boolean two = true; // autoboxing of primitive 'true' to
Boolean type
if (one && two) // auto unboxing do_something ();
Before Java 5.0, the if, while, and do-while statements are all expected as boolean expressions.
Through the use of unboxing, those flow control statements now also accept expressions that
evaluate to Boolean types.
Autoboxing With Switch Statement
Similarly, the old switch statement expects a byte, short, int, or char type in Java 1.4 and earlier to
Java 1.4.
With the addition of autoboxing in Java 5.0, switch now also accepts Byte, Short, Integer, and
Character types.
Operations on Numbers
This is probably the strangest one. You can now use a wrapper type as an operand in operations
where the primitive type is expected.
That means you can apply, say, the increment operator against a reference to an Integer object!
Examples:
Integer i = new Integer(56);
i++;
Integer j = new Integer(4);
Integer k = j + 3;
Assignments
You can assign either a wrapper or primitive to a variable declared as a matching wrapper or
primitive.
For example, a primitive int can be assigned to an Integer reference variable and a reference to an
Integer object can be assigned to a variable declared as an int primitive.
Example: Double d = x;
In the preceding example, x can be either a reference to Double wrapper or double primitive type.
Try It Out
Problem Statement:
Write a program that illustrates the use of Wrapper classes for the primitive types namely int, char,
long, float, double, and boolean.
Code:
public class WrappedClassApp {
public static void main(String args[]) {
Boolean b1 = new Boolean("TRUE");
Boolean b2 = new Boolean("FALSE");
System.out.println(b1.toString() + " or " + b2.toString());
for (int j = 0; j < 16; ++j)
System.out.print(Character.forDigit(j, 16));
System.out.println();
Integer i = new Integer(Integer.parseInt("ef", 16));
Long l = new Long(Long.parseLong("abcd", 16));
long m = l.longValue() * i.longValue();
System.out.println(Long.toString(m, 8));
System.out.println(Float.MIN_VALUE);
System.out.println(Double.MAX_VALUE);
}
}

How It Works:
‰  The program examines some of the more useful methods provided by the wrapped
classes.
‰  It creates two objects of class Boolean from string arguments passed to their
constructors.
‰  It assigns these objects to b1 and b2 and then converts them back to String objects
when it displays them.
‰  They are displayed in lowercase, as boolean values are traditionally represented.
‰  The program then executes a for loop that prints out the character corresponding to
each of the hexadecimal digits.
‰  The static forDigit() method of the Character class is used to generate the character
values of digits in a number system of a different radix.
‰  The static parseInt() and parseLong() methods are used to parse strings according to
different radices.
‰  In the example, they are used to convert strings representing hexadecimal numbers
into Integer and Long values.
‰  These values are then multiplied together and converted to a string that represents the
resulting value in base 8.
‰  This is accomplished using an overloaded version of the toString() method.
‰  The sample program concludes by displaying the minimum float value and the
maximum double value, using the predefined class constants ofthe Float and Double
classes.
‰  The output of the program is as follows:
true or false
0123456789abcdef
50062143
1.4E-45
1.7976931348623157E308
Tips and Tricks:
Typical problems include real-time problems or challenges:
Java 5 (JDK 1.5 and further) includes autoboxing and auto-unboxing. A developer might be
tempted to apply objects such Integer or Double exclusively, abandoning primitives altogether.
For example, it is possible to write code like this:
// A bad use of autoboxing/unboxing!
Double a, b, c;
a = 10.0;
b = 4.0;
c = Math.sqrt(a*a + b*b);
System.out.println(“Hypotenuse is “ + c);
Solution:
‰  In this example, objects of type Double hold values that are used to calculate the
hypotenuse of a right triangle.
‰  Although this code is technically correct, and infact, work properly, it is a very bad use
of autoboxing or unboxing.
‰  It is far less efficient than the equivalent code written applying the primitive double.
‰  The reason is that each autobox and auto-unboxadds overhead that is not present if
the primitive type is used.
‰  In general, you should restrict your use ofthe type wrappers to only those cases in
which the object representation of a primitive type is required.
Summary
‰  As of Java 5, autoboxing / unboxing allow you toconvert primitives to wrappers or to
convert wrappers to primitives automatically.
‰  Using the == with wrappers is tricky; wrapperswith the same small values (typically
lower than 127), will be ==, larger values will not be ==.
Test Your Understanding
1.State true or false for the following:
a)Autoboxing always creates the proper object, and auto-unboxing always produces
the proper value. There is no way for the process to produce the wrong type of
object or value.
b)Using Java 5 (JDK 1.5 and furhter), the method calls such as intValue() or
doubleValue() are very much needed in the code.

No comments:

Post a Comment