I have three short variables. When I add two together and assign the result to the third, eclipse tells me that I need to cast it to a short !
short sFirst, sSecond, sThird;
sFirst = 10;
sSecond = 20;
sThird = sFirst + sSecond;
Hovever, when I do a simple assignment followed by an incremental assignment, all is fine.
short sFirst, sSecond, sThird;
sFirst = 10;
sSecond = 20;
sThird = sFirst;
sThird += sSecond;
Why is this ?
The JLS (§15.8.2) says this:
"The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands."
"Binary numeric promotion is performed on the operands (§5.6.2)."
That means that the operands of your expression are converted to int
. So the addition will add an int
to an int
.
"The type of an additive expression on numeric operands is the promoted type of its operands."
In your case, int
.
I won't speculate as to why it is done this way. However, it is no accident. If you look at the bytecode instruction set as defined in the JVM spec, you will see that there are arithmetic instructions for int
, long
, float
and double
... but NOT for the smaller integer types.
This behavior is precisely specified in the Java Language Specification.
The answer to the question why it was so specified would be just speculation and not a real answer. My "educated guess", backed by Oli Charlesworth's, would be because the equivalent semantics apply to C and other similar languages. And the semantics in C are such (again an "educated guess") because they allow the compiler to produce the most optimal code.
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