I made a little test to manipulate a short and I came across a compilation problem.
The following code compile :
short s = 1;
s += s;
while this one doesn't :
short s = 1;
s = s + s; //Cannot convert from int to short
I've read that shorts are automatically promoted to int, but what's the difference between those two codes ?
You're right that short are promoted to ints. This occurs during the evaluation of the binary operator +, and it's known as binary numeric promotion.
However, this is effectively erased with compound assignment operators such as +=. Section
15.26.2 of the JLS states:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
That is, it's equivalent to casting back to short.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With