so I understand that in java that a value is considered an integer when it is added.
Not necessarily. Not if you're adding long
s, 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 short
s get promoted to int
s, 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:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
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 to
float`.
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
.