Boxing and Unboxing in Java

Collections in Java does not support primitives. We can not store primitives in collection objects. Only objects can be stored in collections.

Below statement is invalid.

//ArrayList<int> list = new ArrayList<>();

But still we can store integers in ArrayList using a concept called as Boxing. Process by which primitives like int are converted into objects of Wrapper classes like Integer, Double etc is called as Boxing. The reverse process is called as Unboxing.

Below example illustrates Boxing and Unboxing in Java.

package boxing;

import java.util.ArrayList;

/**
 * Created by ssalunke on 19/04/2016.
 */
public class Boxing {

    public static void main(String args []){

        //Below statement is invalid
        //ArrayList<int> list = new ArrayList<>();

        int c = 3;

        ArrayList<Integer> list = new ArrayList<>();
        list.add(2); //boxing to Integer wrapper
        list.add(c); //boxing to Integer wrapper

        //Unboxing occurs when storing integer object to primitive type
        int a = list.get(0);
        System.out.println("First value in list is " + a);
    }
}

Here is the output of above example.
First value in list is 2

You may also like...