Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short plus short is an int [duplicate]

Tags:

java

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 ?

like image 466
Simon Avatar asked Dec 20 '22 02:12

Simon


2 Answers

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.

like image 158
Stephen C Avatar answered Jan 05 '23 09:01

Stephen C


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.

like image 20
Marko Topolnik Avatar answered Jan 05 '23 10:01

Marko Topolnik