Wrapper Classes
When we give the
gifts, we wrap them nicely
in the
box. The glossy paper around a box makes in attractive.
we have worked with simple data types. Now java
wants to
wrap them and make them more attractive
(useful). For
this java uses
interesting concept of wrapper class.
Vector cannot handle
primitive (basic) data types
like int, float, long, char and double. Vector can accept the data in the form of objects. Therefore there is
need to convert basic data types
into equivalent objects. So this conversion is
done by using the
wrapper classes which are present in java.lang package.
As all
these numbers are stored
as objects, they take all the advantage of Object
oriented technology.
They can be passed to methods as
parameters.
METHODS UNDER WRAPPER CLASSES
1) Converting basic data type to Numeric Object using Constructor Method
int i = 10;
float f = 8.9f;
double d = 897678.9878;
long l = 989456767;
Integer intobj = new
Integer(i); // convert integer to Integer Object
Double doubleobj=
new Double(d); // convert double to Double Object
Float floatobj= new Float(f); // convert
float to Float Object
Long longobj=
new Long(1);
//converts long to Long object
2) Converting Numeric Object to basic data type using typeValue()
method.
int i = intobj. intValue(); // converts Integer object to basic integer
float f = floatobj. floatValue(); //
converts Float object to basic float
long 1 = longobj.
longValue(); // converts Long object to basic long
double d = doubleobj. doubleValue(); //
converts Double object to basic double
3) Converting basic data type to the string using
static method toString().
String strl
= Integer.toString(i); // primitive integer to string
String str2 = Float.toString(f); // primitive float to
string
String str3 = Double.toString(d); // primitive double to string
String str4 = Long.toString(1); // primitive long to string
4) Converting String Objects to Numeric Objects using the static method ValueOf()
String s1 = "100";
String s2 = "10.54";
String s3 = "
12345";
String s4 = "312223.44222";
Integer objl = Integer. ValueOf(s1); // converts string
to Integer Object
Float obj2 = Float.valueOf(s2); // converts String to Float Object
Long obj3
= Long.valueOf(s3); // converts
String to
Long Object
Double obj4= Double.valueof(s4); // converts String
to Double Object.
5) Conversion of Numeric Strings to basic data type using
passing methods
int i = Integer.parseInt(strl);
float f = Float.parseFloat(str2);
double d = Double.parseDouble(str3);
long 1 = Long.parseLong(str4);
Example:
class WrapperDemo {
public static void
main(String[]
args) {
int i = 10;
float f = 10.85f;
double d = 0.25632;
long ph = 98756;
Integer IntVal = new Integer(i);
Float FloatVal = new Float(f);
Double DoubleVal = new Double(d);
Long LongVal = new Long(ph);
System.out.println(IntVal);
System.out.println(FloatVal);
System.out.println(Double Val);
System.out.println(LongVal);
}
}
Post a Comment