Skip to main content

Q) What are wrapper classes?




A)
->for each primitive data type a corresponding java class is given in java.long.package.
These 8 library classes corresponding to 8 primitive data types are known as wrapper class.
->An instance of wrapper class wraps (encapsulates) a primitive value and hence the name.

Primitive data type
Wrapper class
int
Integer
byte
Byte
short
Short
long
Long
float
Float
double
Double
char
character
boolean
Boolean

->the java is not purely 100% object oriented, because it contains primitive data types. If any language contains primitive data types then that language is not pure object oriented.
->but the pure object oriented language is smalltalk.
->Wrapper object:
Object oriented manner an object is encapsulate the primitive value. That object is called wrapper object.
Ex:
Int a=10;
Integer i=nre Integer(10);
->to convert a primitive value into wrapper object create the object of wrapper class by supplying primitive alue as argument to the parameterized constructor of the wrapper class.
Ex:
Integer i= new Integer(10);
Boolean b=new Boolean(true);
Float f= new Float(1.1);
Double d=new Double(2.5);

->By calling xxxvalue(); method on the wrapper object we can get the primitive value.
Ex:
int a= i.intValue();
boolean flag= b.booleanValue();
double b=d.doubleValue();

-> Conversion of object type to primitive type.
->integer i=new Integer(10);  then the Integer class of encapsulated in the Integer object.

Ex:
class wrapperclass {
       public static void main(String[] args) {
                     Integer i=new Integer(10);
                     int c=40;
                     //intb=i.intValue(10);
                     int b=i+c; //doesn't work before jdk 1.5
                     System.out.println("b: "+b);
       }
}

Output:
b: 50

->implicit conversion of wrapper object to primitive type is known as auto unboxing. It is introduced in jdk1.5.
int b=i+c;
->in the above statement, Integer object I is implicitly converted into primitive value then arithmetic operation is performed. I.e. auto unboxing is implemented and then addition is performed.

Comments