Tuesday, 27 August 2013

Wrapper class



Wrapper class

Wrapper class were a solution of the primitive data type not being a part of object oriented approach of java….like being returned from a method as a method.
Java allows you to include the primitives in the family of objects by using what are called wrapper classes
There is a wrapper class for every primitive in java.. the wrapper class for int is Integer, for float is Float.
The wrapper classes in the Java API serve two primary purposes:
  • To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  • To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapper class with the new operator or by invoking a static method on the wrapper class.
Creating wrapper object with new operator
Primitive datatype-->Wrapper Class-->Constructor arguments
  • boolean--> Boolean--> boolean or String
  • byte--> Byte--> byte or String
  • char--> Character--> char
  • short--> Short--> short or String
  • int-->Integer--> int or String
  • long--> Long--> long or String
  • float-->Float--> float double or String
  • double-->Double--> double or String
All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the wrapper classes except Boolean and Character are subclasses of an abstract class called Number, whereas Boolean and Character are derived directly from the Object class.All of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation of the type being constructed.
Boolean wboo = new Boolean("false");
Boolean yboo=new Boolean(false);
Character c1 = new Character('c');
Note that there is no way to modify a wrapped value—that is, the wrapped values are immutable. To wrap another value, you need to create another object.

WRAPPING PRIMITIVES USING A STATIC METHOD
All wrapper classes offers static valueOf() methods which give you another approach to creating wrapper objects. Because it's a static method, it can be invoked directly on the class (without instantiating it), and will return the corresponding object that is wrapping what you passed in as an argument.
this method  take a String representation of the appropriate type of primitive as its first argument, it also takes an additional argument, int radix, which indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented
Integer i2 = Integer.valueOf("101011", 2);  // converts 101011 to 43 and assigns the
                                           // value 43 to the Integer object i2

USING WRAPPER CONVERSION UTILITIES
xxxValue() method
When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numeric wrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numeric type.
Integer i2 = new Integer(42);  //  make a new wrapper object
byte b = i2.byteValue();         //  convert i2's value to a byte primitive
short s = i2.shortValue();      //  another of Integer's xxxValue methods
double d = i2.doubleValue(); //  yet another of Integer's xxxValue methods

xxx Parsexxx(String) method
If you do not need to store a value in a wrapper but just want to convert the type , you can do it by using an appropriate static method of the appropriate wrapper class. For example, all the wrapper classes except Character offer a static method that has the following signature:
static <type> parse<Type>(String s)
The <type> may be any of the primitive types except char (byte, short, int, long, float, double, or boolean), and the <Type> is the same as <type> with the first letter uppercased;
String s = "123";
int i = Integer.parseInt(s);


parseXxx() and valueOf()
·  parseXxx() returns the named primitive.
·  valueOf() returns a newly created wrapped object of the type that invoked the method.
double d4 = Double.parseDouble("3.14");     // convert a String to a primitive
System.out.println("d4 = " + d4);               // result is  "d4 = 3.14"
Double d5 = Double.valueOf("3.14");         // create a Double object
System.out.println(d5 instanceof Double ); // result is "true"

toString() method
All of the wrapper classes have a no-arg, nonstatic, instance version of toString(). This method returns a String with the value of the primitive wrapped in the object—
Double d = new Double("3.14");
System.out.println("d = " + d.toString() );    //  result is "d = 3.14"
All of the numeric wrapper classes provide an overloaded, static toString() method that takes a primitive numeric of the appropriate type (Double.toString() takes a double), and, of course, returns a String with that primitive’s value.
System.out.println("d = " + Double.toString(3.14);    // result is "d = 3.14"
Integer and Long provide a third toString() method. It is static, its first argument is the appropriate primitive, and its second argument is a radix. The radix argument tells the method to take the first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, then return the result as a String
System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe"

toXxxString() method(Binary, Hexadecimal, Octal)
The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. These conversion methods, toXxxString(), take an int or long, and return a String representation of the converted number,
String s3 = Integer.toHexString(254);       // convert 254 to hex
System.out.println("254 in hex = " + s3);   // result is "254 in hex = fe"
String s4 = Long.toOctalString(254);        // convert 254 to octal
System.out.println("254 in octal = "+ s4);  // result is "254 in octal = 376"
Quick review
  • Java uses primitive types, such as int, char, double to hold the basic data types supported by the language.
  • Sometimes it is required to create an object representation of these primitive types.
  • These are collection classes that deal only with such objects. One needs to wrap the primitive type in a class.
  • To satisfy this need, java provides classes that correspond to each of the primitive types. Basically, these classes encapsulate, or wrap, the primitive types within a class.
  • Thus, they are commonly referred to as type wrapper. Type wrapper are classes that encapsulate a primitive type within an object.
  • The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float.
These classes offer a wide array of methods that allow to fully integrate the primitive types into Java’s object hierarchy.

Wrapper classes for converting simple types

Simple Type
Wrapper class
boolean
Boolean
char
Character
double
Double
float
Float
int
Integer
long
Long

Converting primitive numbers to Object numbers using constructor methods

Constructor calling
Conversion Action
Integer IntVal = new Integer(i);
Primitive integer to Integer object
Float FloatVal = new Float(f);
Primitive float to Float object
Double DoubleVal = new Double(d);
Primitive double to Double object
Long LongVal = new Long(l);
Primitive long to Long object

NOTE : I, f, d and l are primitive data values denoting int, float, double and long data types. They may be constants or variables.

Converting Object numbers to Primitive numbers using typeValue() method

Method calling
Conversion Action
int i = IntVal.intValue();
Object to primitive integer
float f = FloatVal.floatValue();
Object to primitive float
double d = DoubleVal.doubleValue();
Object to primitive double
long l = LongVal.longValue();
Object to primitive long

Converting Numbers to Strings using toString() method

Method calling
Conversion Action
str = Integer.toString(i);
Primitive integer i to String str
str = Float.toString(f);
Primitive float f  to String str
str = Double.toString(d);
Primitive double d to String str
str = Long.toString(l);
Primitive long l to String str

Converting String Object in to Numeric Object using static method ValueOf()

Method calling
Conversion Action
IntVal = Integer.ValueOf(str);
Convert String into Integer object
FloatVal = Float.ValueOf(str);
Convert String into Float object
DoubleVal = Double.ValueOf(str);
Convert String into Double object
LongVal = Long.ValueOf(str);
Convert String into Long object

Converting Numeric Strings to Primitive numbers using Parsing method

Method calling
Conversion Action
int i = Integer.parseInt(str);
Converts String str into primitive integer i
long l = Long.parseLong(str);
Converts String str into primitive long l

NOTE : parseInt() and parseLong() methods throw a Number Format Exception if the value of the str does not represent an integer. 


0 comments:

Post a Comment