Reputation: 335
I really find the concept of conversion to be confusing.
short a = 34;
short b = (short)34;
What is the linguistic difference between these two statements? I think that, in the first statement the int literal 34 is directly stored in the short variable a, causing a conversion of int literal 34 to short literal 34. And in the second one, it seems that the int literal 34 is first converted to the short literal 34 due to the casting instruction and then stored in the short variable b. Am i correct or its one of the two cases?
Upvotes: 1
Views: 53
Reputation: 718836
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:
byte
, char
or short
, ANDThis 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.
Upvotes: 1