In Java we can't put primitive values into a collection. Collections can only hold object references. So Java provide the wrapper classes and user has to change the primitive values to the respective wrapper class objects like int is converted into Integer Objects. This is know as Boxing. In Jdk1.5 or above this boxing is done by the compiler. So now programmers are not needed to convert the primitive values to any objects. It is automatically done by Java.


 


The following example illustrates autoboxing and unboxing


 


package com.visualbuilder;


import java.util.ArrayList;


public class AutoboxingExample {


/**
* @param args
*/

public static void main(String[] args) {
        ArrayList list = new ArrayList();
    //Adding int
    list.add(10);
    //Adding float
    list.add(10.4f);
    //Adding double
    list.add(10.0);
    //Adding character
    list.add('c');
    for(int i=0;i< list.size();i++){
                System.out.println(list.get(i));
        }
    }


}


 


Output:-


 


The following output will be displayed on console.


10
10.4
10.0
c
                    

Copyright © 2013 VisualBuilder. All rights reserved