Monday, 8 August 2016

java - short plus short is an int




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 ?



Answer



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.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...