Originally posted by J�rg Waldmann:
... Is there another situation where the implicit cast is NOT done? ...
Yes.
Basically, if a variable is final with its value known at compile time, then it can be assigned to a narrower primitive type if it fits within range. This implies that if the variable is not final and/or its value is not known at compile time and/or it does not fit within range, then the conversion ("implicit cast") will not work.
Or in the language of the JLS...
"...if the expression is a constant expression ... 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." (Ref:
5.2.)
So what is a "constant expression" in this case?
"A compile-time
constant expression is an expression denoting a value of primitive type ... that ... is composed using ... literals of primitive type ... [or] simple names that refer to constant variables..." (Ref:
15.28.)
And what is a "constant variable"?
"We call a variable ... of primitive type ... that is final and initialized with a compile-time constant expression ... a
constant variable." (Ref:
4.12.4.)
Note: In quoting the JLS, I omitted parts (...) in order to focus only on
primitive assignment conversions. In particular, I highlighted only two of several bulleted items that constitute a "constant expression."
[ April 15, 2006: Message edited by: marc weber ]