Why does the assignment of a short variable to an Integer reference produce a compile time error?

kauray picture kauray · Nov 23, 2015 · Viewed 15.8k times · Source

I have the following code in Java :

class Boxing
    {
        public static void main(String args[])
        {
            short s = 10;
            Integer iRef = s;
        }
    }

Why does it produce an error in compilation? If I explicitly typecast the short to an integer in the expression, it compiles successfully. Since I'm using a short in an expression isn't the type of that supposed to be an integer by default without requiring the explicit case?

Answer

Thilo picture Thilo · Nov 23, 2015

You want to have two things happening here: widening and auto-boxing.

Unfortunately, Java does only one of the two automatically. The reason for that is most likely that autoboxing was introduced fairly late (in Java5), and they had to be careful to not break existing code.

You can do

int is = s;    // widening

Short sRef = s;   // autoboxing

Integer iRef = (int) s;  // explicit widening, then autoboxing