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

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 433
    Comment on it

    INTRODUCTION:

    The automatic conversion made by the Java compiler between primitive types and their corresponding object wrapper classes, is known as Autoboxing

    It allows us to use primitive and object type interchangeably in Java on many places like assignment, method invocation etc

    For example

    A primitive type like int gets automatically converted into corresponding wrapper class object e.g. Integer because primitive is boxed into wrapper class.

    If the conversion goes the other way, this is called unboxing. Ex.: If Integer object is converted into primitive int.

    Benefits of Autoboxing & Unboxing:

    1. Less coding is required since there is no need of conversion between primitives and Wrappers manually
    2. Autoboxing makes working with the Collections Framework much easier.
    3. With autoboxing it is no longer necessary to manually construct an object in order to wrap a primitive type.
    4. It helps prevent errors, but may lead to unexpected errors hence should be used carefully.

    Example for Autoboxing :

    class Example1{  
      public static void main(String args[]){  
        int a=10;  
            Integer a2=new Integer(a);//Boxing  
    
            Integer a3=8;//Boxing  
    
            System.out.println("values wil be" + a2+" "+a3);  
     }   
    }  
    

    Output: 10 8

    Example for unboxing:

    class Example2{  
      public static void main(String args[]){  
        Integer i=new Integer(100);  
            int a=i;  
    
            System.out.println(a);  
     }   
    }  
    

    output: 100

    References:

    http://www.javatpoint.com/autoboxing-and-unboxing

 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: