Dishi Jain wrote:
Why can't the second one as well follow the same steps?
"widening to int, then boxing" , while //Line 4 gives compilation error!!!
Is it like while assigning non-constant variable Casting is required?
In your case, Line 1 would give a compilation error, 'cause of the incompatibility; and yes non-constant variable when narrowing need casting.
gaurav gupta sitm wrote:widening followed by boxing not allowed
The thumb rule states that, "Autoboxing occurs strictly between the primitive datatype and its wrapper class only", not to be confused with widening and casting.
In the above code, line 1 would compile only if you explicitly cast the float to a double.
Be careful of trying to figure out what combination of widening, narrowing, and auto-boxing are allowed, based on compile time constants. Compile time constants has special rules that allow certain combinations to be allowed that isn't allowed without compile time constants.
Like Henry said, there are some special rules for compile time constants which do not follow the general rules. I'm not exactly sure, but I believe that when you assign a constant to a wrapper variable, it will work as long as you are using integral types, smaller than Long.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
is working fine for me. No compile time errors.
Because as per the description in Khalid Mughal, widening and then Boxing is taking place, while it is not legal.
Stephan van Hulst wrote:Like Henry said, there are some special rules for compile time constants which do not follow the general rules.
Anyway... interestingly, there are no byte or short compile time constants. Byte and short compile time constants are just int compile time constants.
Literals are compile time constants. A "10" is a int compile time constant. A "(short) 10" is actually not a short compile time constant, but is actually an int compile time constant that has been truncated to a short value (which is still 10 here). And... assigning this int compile time constant to an Integer reference just does boxing (and nothing else).