To provide a mechanism to "wrap" primitive values in an object so that the primitives can be included in activities reserved for objects, like being added to Collections, or returned from a method with an object return value.
Wrapper objects are immutable. Once they have been given a value, that value cannot be changed.
The Wrapper Constructors:
Integer i1 = new Integer(42);
Integer i2 = new Integer("42");
Float f1 = new Float(3.14f);
Float f2 = new Float("3.14f");
Character c1 = new Character('c');//only one constructor
Boolean b = new Boolean("false");//can take true/false/string
THE valueOf() METHOD:
static valueOf() method provided in most of the wrapper classes give you another approach to creating wrapper objects.
e.g.
Float f2 = Float.valueOf("3.14f");
assigns 3.14 to the Float object f2.
Integer i2 = Integer.valueOf("101011",2);//the 2nd argument indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented.
converts 101011 to 43 and assigns the value 43 to the Integer object i2.
THE 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 noarg methods.
e.g
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
THE parseXxx() METHOD:
It can convert String objects from different bases (radix), when the underlying
primitive type is any of the four integer types.
e.g.
String str="bhabani";
int x=Integer.parseInt(str);
DIFFERENCE BETWEEN parseXXX() and valueOf() :
The six parseXxx() methods (one for each numeric wrapper type) are closely related to the valueOf() method that exists in all of the numeric wrapper classes. Both parseXxx() and valueOf() take a String as an argument, throw a NumberFormatException (a.k.a. NFE) if the String argument is not properly formed,
The difference between the two methods is
■ parseXxx() returns the named primitive.
■ valueOf() returns a newly created wrapped object of the type that invoked
the method.
THE toString() METHOD:
We can use this toString() with every class because this method is under java.lang.String and every class inherits it.
We can convert any object to String by this method.
e.g.
Integer x=new Integer(5);
String str=x.toString();
THE toXxxString() METHOD:
Xxx can be referred to (Binary, Hexadecimal, Octal).
e.g.
String str=Integer.toBinaryString(100);
outputis- 1100100
String s3 = Integer.toHexString(254);
String s4 = Long.toOctalString(254);
primitive xxxValue() - to convert a Wrapper to a primitive
primitive parseXxx(String) - to convert a String to a primitive
Wrapper valueOf(String) - to convert a String to a Wrapper
No comments:
Post a Comment