Reputation: 55
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
Upvotes: 3
Views: 82
Reputation: 1074385
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 todouble
.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 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
.
Upvotes: 6