Monday, 6 February 2012

Wrapper classes

Wrapper classes correspond to the primitive data types in the Java language. These classes represent the primitive values as objects. All the wrapper classes except Character have two constructors -- one that takes the primitive value and another that takes the String representation of the value. For instance:

Integer i1 = new Integer(50);
Integer i2 = new Integer("50");


The Character class constructor takes a char type element as an argument:

Character c = new Character('A');


Wrapper objects are immutable. This means that once a wrapper object has a value assigned to it, that value cannot be changed.

The valueOf() method


All wrapper classes (except Character) define a static method called valueOf(), which returns the wrapper object corresponding to the primitive value represented by the String argument. For instance:

Float f1 = Float.valueOf("1.5f");


The overloaded form of this method takes the representation base (binary, octal, or hexadecimal) of the first argument as the second argument. For instance:

Integer I = Integer.valueOf("10011110",2);



Converting wrapper objects to primitives


All the numeric wrapper classes have six methods, which can be used to convert a numeric wrapper to any primitive numeric type. These methods are byteValue, doubleValue, floatValue, intValue, longValue, and shortValue. An example is shown below:

Integer i = new Integer(20);
byte b = i.byteValue();



Parser methods


The six parser methods are parseInt, parseDouble, parseFloat, parseLong, parseByte, and parseShort. They take a String as the argument and convert it to the corresponding primitive. They throw a NumberFormatException if the String is not properly formed. For instance:

double d = Double.parseDouble("4.23");


It can also take a radix(base) as the second argument:

int i = Integer.parseInt("10011110",2);



Base conversion


The Integer and Long wrapper classes have methods like toBinaryString() and toOctalString(), which convert numbers in base 10 to other bases. For instance:

String s = Integer.toHexString(25);


We discussed the usage and signature of the various utility methods of the Math class. You are expected to memorize these for the exam. We also saw how String objects are immutable, while StringBuffer objects are not. The wrapper classes provide utility methods that allow you to represent primitives as objects. Make sure you are familiar with all the parsing and conversion methods.

No comments:

Post a Comment