If short
is automatically promoted to int
in arithmetic operations, then why is:
short thirty = 10 * 3;
A legal assignment to the short
variable thirty
?
In turn, this:
short ten = 10;
short three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED
as well as this:
int ten = 10;
int three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED
does not compile because assigning an int
value to a short
is not allowed without casting as expected.
Is there something special going on about numerical literals?
Because the compiler replaces
10*3
with 30 at compile time itself. So,effectively :short thirty = 10 * 3
is calculated at compile time.Try changing
ten
andthree
tofinal short
(making them compile time constants) and see what happens :PExamine byte-code using
javap -v
for both verisions (10*3
andfinal short
). You will be able to see that there is little difference.Ok, So, here is the byte code difference for different cases.
Case -1 :
Byte code :
Case -2 :
Byte code :
Case -3 :
Byte-code :
In the above case,
10
and3
are taken from the local variabless1
ands2