Hi Peter,
You're right; my previous answer was not sufficiently precise. Again, I refer you to the JLS for the full set of rules that Java applies. But here are clarifications for your specific questions:
Originally posted by Peter Ricke:
why can`t i compile
Float f = 5.0; //not ok
from my point of view, i`m trying here to narrow and than box.
OK, maybe double cannot be narrowed to float but
Integer i = 3L; also does not work. (Narrowing also not possible here?)
The automatic narrowing followed by boxing applies only to variables of type Byte, Short, and Character. Here's the rule stated in the JLS:
In addition, if the expression is a constant expression (�15.28) of type byte, short, char or int :
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
-A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is :
Byte and the value of the constant expression is representable in the type byte.Short and the value of the constant expression is representable in the type short.Character and the value of the constant expression is representable in the type char.
why does my 2nd example
Short s2 = (byte)5;
compile ? I am widening (from byte to short) or am I not?
This seems to be an application of the same rule I quoted above, though I admit that I'm not 100% sure of this. I'll see if I can look up a more precise explanation.
[ December 13, 2007: Message edited by: Kelvin Lim ]