wybrand wrote:
> Can you please give me an answer to the following??
>
> See next code-fragment:
>
> class a {
>
> public static void main( String [] arg ) {
> short a;
> int b;
>
> // Implicit cast.
> a = 65;
>
> // Explicit cast which compiles.
> a = (int)65;
>
> // Explicit cast which does not compile.
> b = (long)65;
> }
> }
>
> The first statement compiles because of implicit typecasting and there
> is no loss of information (65 < 2^16-1).
There is no such thing as "implicit typecasting". What you see is the
operation of "assignment conversion"; see below for more information.
> The third one does not compile because we do an explicit typecast and
> a long is 64 bytes and an integer is 32.
There is only one kind of typecast, which in fact does appear in the
third expression. Whether or not there is a cast is not directly
relevant, however: what is relevant is the _type_ of the expression
being assigned. In that respect there is no difference whatsoever
between "b = (long) 65;" and "b = 65L;".
> Why does the second statement compile?? A integer doesn't fit in a
> short, just like a long does not fit in a integer (third statement).
> It looks like if a implicit typecast takes place just like the fist
> statement.
Again, there is no such thing as an "implicit typecast". As you have
discovered, there is no difference from the point of view of the
assignment operator between "a = 65;" and "a = (int) 65;".
Here is the definitive material, from JLS(2e), section 5.2:
Assignment conversion occurs when the value of an expression is assigned
(§15.26) to a variable: the type of the expression must be converted to
the type of the variable. Assignment contexts allow the use of an
identity conversion (§5.1.1), a widening primitive conversion (§5.1.2),
or a widening reference conversion (§5.1.4). In addition, a narrowing
primitive conversion may be used if all of the following conditions are
satisfied:
* The expression is a constant expression of type byte, short, char
or int.
* The type of the variable is byte, short, or char.
* The value of the expression (which is known at compile time,
because it is a constant expression) is representable in the type of the
variable.
Compare those rules to your examples to see that the observed behavior
of the compiler is completely in conformance with the JLS.
John Bollinger