Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting values and resulting math

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

like image 711
Borla312 Avatar asked Jun 18 '26 10:06

Borla312


1 Answers

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.

like image 192
T.J. Crowder Avatar answered Jun 21 '26 01:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!