Java - What is the output: Autoboxing/Unboxing, Collections and Object

Question

What is the output of the following code:

List list = new ArrayList();
list.add(101); // Autoboxing will work here
Integer a = (Integer)list.get(0);
int aValue = list.get(0);


Click to view the answer

int aValue = list.get(0); // autounboxing won't compile

Note

Because the return type of the get() method is Object, the last statement would not work.

Unboxing happens from a primitive wrapper type (Integer) to its corresponding primitive type (int).

Unboxing doesn't happen between Object reference type and an int primitive type.

Here is the fix

Demo

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(101); // auto boxing will work
    int aValue = list.get(0); // auto unboxing will work, too

    System.out.println(aValue);/*from ww  w  .j a v a  2  s .c o  m*/
  }

}

Result

Related Quiz