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
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:
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 todouble.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 tolong.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With