Tuesday, 10 January 2017

Wrapper class in Java

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive. Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
============================
primitive ||   Wrapper Class
============================
boolean  --> Boolean
char        --> Character
int           --> Integer
long        --> Long
double    --> Double
=============================
eg-1.Wrapper class Example: Primitive to Wrapper

    public class WrapperExample1{  
    public static void main(String args[]){  
    //Converting int into Integer  
    int a=20;  
    Integer i=Integer.valueOf(a);//converting int into Integer  
    Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
      
    System.out.println(a+" "+i+" "+j);  
    }}  

Output:

20 20 20

eg-2. Wrapper class Example: Wrapper to Primitive

    public class WrapperExample2{    
    public static void main(String args[]){    
    //Converting Integer to int    
    Integer a=new Integer(3);    
    int i=a.intValue();//converting Integer to int  
    int j=a;//unboxing, now compiler will write a.intValue() internally    
        
    System.out.println(a+" "+i+" "+j);    
    }}    

Output:

3 3 3
---------

That's okay? But why wrapper classes necessary in java. 

The Java designers kept the two separate to keep things simple. You use the wrappers when you need types that fit in the object oriented world - like polymorphism, collections etc. You use the primitives when you need efficiency.

No comments:

Post a Comment