4

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 ?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Simon
  • 2,208
  • 4
  • 32
  • 47

2 Answers2

9

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.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you Stephen. Having come from a C/C++ background (over 20 years), this kind of restriction seems like an aberration which should really be handled by the compiler rather than the programmer. – Simon Aug 07 '13 at 11:53
2

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • One very plausible answer to "why" is "because it echos the semantics of other C-like languages"... – Oliver Charlesworth Aug 07 '13 at 10:22
  • @OliCharlesworth Which, my guess, would be because it gives the widest lattitude to the compiler to produce optimal code (i don't mean javac, of course). – Marko Topolnik Aug 07 '13 at 10:24
  • However, in C or C++ you would never need to cast the addition of two shorts to a short – Simon Aug 07 '13 at 11:51
  • 1
    @Simon You mean *explicitly cast*. That's just a syntactic finesse, and it's there due to Java's "protect the programmer from himself" attitude. – Marko Topolnik Aug 07 '13 at 12:15