Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Autoboxing and Unboxing in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 360
    Comment on it

    Autoboxing

    Autoboxing is a feature introduced in Java 5 and can be defined as converting primitive data type into it's equivalent wrapper type automatically. In Java,for every primitive type there is a corresponding class of reference type and these classes are called wrapper class. For e.g: int primitive type is converted to Integer wrapper type in autoboxing. Autoboxing is used whenever a primitive type is to be treated as an object i.e instead of object a primitive type is available then it is converted to object. For e.g: ArrayList class requires an object reference.

    ArrayList<Integer> intList = new ArrayList<Integer>();
    intList.add(1); //autoboxing - primitive to object
    intList.add(2); //autoboxing

    Program to demonstrate Autoboxing:

    class AutoBoxingExample
    {  
      public static void main(String args[])
       {  
        int a=50;
        //passing a primitive type(int) to wrapper type(Integer),automatic conversion autoboxing 
        Integer a2=new Integer(a);  
      
            Integer a3=5;//autoboxing  
              
            System.out.println(a2+" "+a3);  
     }   
    }  

    Output: 

    50 5

    Unboxing

    Unboxing is a feature introduced in Java 5 and can be defined as converting wrapper type into it's equivalent primitive type automatically.

    Program to demonstrate Unboxing:

    class UnboxingExample
    {  
      public static void main(String args[])
      {  
        Integer i=new Integer(50);  //Integer wrapper class is used
    
            int a=i;    // Unboxing
              
            System.out.println(a);  
     }   
    }  

    Output:

    50

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: