Saveendra Ekanayake
Saveendra Ekanayake

Reputation: 3313

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);
    }
}

Upvotes: 1

Views: 1518

Answers (2)

M A
M A

Reputation: 72844

int y = x + iob1;

The + operator cannot have an int and an Object (How do you expect to add a number to an object?). See this section from the Java Language Specification:

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

Upvotes: 1

user4668606
user4668606

Reputation:

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.

Upvotes: 4

Related Questions