Search code examples
javaboxingunboxing

Autoboxing Unboxing in java using Object


Using Object type object for autoboxing is working but it is not working for unboxing. What is the reason behind it. I mean about not working of unboxing feature for Object type object. Is any special reason to implement this behaviour. Because its support autoboxing but not support unboxing.When it comes to Integer class it support both autoboxing and unboxing. And c# also supports autoboxing and unboxing for Object type object.

class Demo{
    public static void main(String args[]){

        int x=100;
        Object iob1=new Object();

        Object iob2=x;  //Auto Boxing

        System.out.println(iob2.toString());

        int y = x + iob1;   //Unboxing is not working
        int z = x + new Integer(10); // Unboxing is working
        System.out.println(y);
    }
}

Solution

  • Unboxing is working quite fine. BUT only for Double, Integer, etc.. iob1 is of type Object, so it can't work. The jls lists types that can be un-/boxed here.