What is the functional difference between these two statements?
There is no functional difference in this example. In this example, the end result is the same.
From a (Java) linguistic perspective, these are two distinct cases:
short b = (short) 34;
The number 34
is an int
literal. The (short)
is a type cast that performs an explicit narrowing primitive conversion. This will truncate the value if necessary, though it is not necessary here. You then have an short
value that is assigned to the variable with no further conversion.
short b = 34;
The number 34
is an int
literal. In this case there is an implicit narrowing primitive conversion. This "special case" happens in an assignment context when:
- the expression being evaluated is a compile time constant expression, AND
- the type of the variable is
byte
, char
or short
, AND
- the value of the expression is representable in the type of the variable.
This will NOT truncate the value.
If you change the code to the following, then the difference between the two contexts becomes apparent:
short a = 100000; // Compilation error because 100,000 is too large
short b = (short) 100000; // OK - 100,000 is truncated to give -31,072
Alternatively:
int x = 34;
short y = x; // Compilation error because 'x' is NOT
// a constant expression
The most relevant sections of the JLS are 5.2 Assignment Contexts and 5.4 Casting Contexts.