3
short x, y; 
short z = ((short)x) + ((short)y); 

So I understand that in Java that a value is considered an integer when it is added. It's just one of the nuances in the language. However, here, I am already casting short to the variables x and y and it still gives me an error saying that

can't convert from int to short

Tom
  • 16,842
  • 17
  • 45
  • 54
Borla312
  • 55
  • 4

1 Answers1

6

so I understand that in java that a value is considered an integer when it is added.

Not necessarily. Not if you're adding longs, for instance.

However, here, I am already casting short to the variables x and y and it still gives me an error saying that can't convert from int to short.

That's because you're casting the values before they're added; the result of the + is still an int. (In fact, (short)x is a no-op; x is already a short.)

The correct way to write that is:

short z = (short)(x + y);

The shorts get promoted to ints, added together, and then we cast the result back down to a short.

Re your comment:

(I'm) not sure why first casting the x and the y to short and putting them into parentheses would not result in short + short addition

Because Java doesn't have short + short addition. The smallest size it does addition on is int, because the first thing the "additive" operators (+ and -) do is binary numeric promotion:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    • If either operand is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted tofloat`.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

So short + short (or char + char, or byte + byte) becomes int + int yielding int. The only integer additions Java has are int + int => int and long + long => long.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I understand what you are saying but I am still logically not sure why first casting the x and the y to short and putting them into parentheses would not result in short + short addition. Does the casting take place separately for x and y, then java AGAIN converts them back to int? – Borla312 Oct 03 '15 at 17:55
  • @Borla312: *"not sure why first casting the x and the y to short and putting them into parentheses would not result in short + short addition"* Because Java *doesn't have* short + short addition. I've expanded the answer to clarify that. – T.J. Crowder Oct 03 '15 at 22:11
  • thank you for the very thorough, detailed, and clear explanation TJ! – Borla312 Oct 04 '15 at 22:39
  • @Borla312: No worries, hope that helped. – T.J. Crowder Oct 05 '15 at 04:44