JSpiders - Wrapper classes
-
Upload
jspiders-basavanagudi -
Category
Software
-
view
100 -
download
1
Transcript of JSpiders - Wrapper classes
WRAPPER CLASSES
• Java is not pure object oriented.• Any language which makes use of primitive
type of data such languages are not object oriented.• Few purely object oriented languages are Ex: Scala, Smalltalk, Eiffel ..etc• The primitive data types are not objects, they
do not belong to any class.• Sometimes, it is required to convert data types
into objects in Java language.• A data type can be converted into an object and
then used with the help of Wrapper Classes.
What are Wrapper classes?• A wrapper class wraps (encloses) around
a data type and gives it an object appearance.
• Wherever, the data type is required as an object, Wrapper class object can be used.
• Wrapper classes include methods to unwrap the object and give back the data type.
• It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
To wrap (or to convert) each primitive data type, there comes a wrapper class. Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.
Wrapper Classes Hierarchy
• All wrapper classes are final classes.• All Wrapper classes implements comparable type.• All wrapper classes overrides 3 object class methods
1.toString()2.hashCode()3.equals(Object obj)
Conversion of primitive data to object type is known as Boxing.EX: int k = 100;
Integer it1 = new Integer(k);double d = 3.3;Double dt2= new Double(d);
Conversion of Object type of data to Primitive type is called as Un-Boxing.
EX: int m = it1.intValue();System.out.println(m); // prints 100double n = dt2.doubleValue(); System.out.println(n); // prints 3.3
Boxing and Un-Boxing Can be done implicitly by compiler, it is known as Auto Boxing and Auto Un-Boxing.
Integer a1=30; Auto Boxing int l= a1; Auto Un-Boxing
Wrapper Classes In Collection FrameWorks• Wrapper Classes are used in collection framework.• In Collection we can add only Object type of data.• If primitive data added in Collection Framework then auto boxing and
auto un-boxing both happens Implicitly.Ex: ArrayList a1 = new ArrayList(); a1.add(12);
a1.add(2356); a1.add(4.5);
• Here First auto boxing happens and then up-casting to Object class happens.
Parsing Technique• Conversion of String type of data to Number format is called as Parsing • For Parsing we make use of parseX() methods which are present in Wrapper
classes.
Ex:
String str = “1234”;
int i = Integer.parseInt(str);
System.out.println(i); // 1234
• Parsing has to be done carefully, else we may get Exception.• In previous example if String value is “1234g” ,in this case during parsing the
value doesn’t match with Integer hence we get NumberFormatException.