1

I have this piece of code.

        short x = 50,y=40;
        short z = (short)(x + y);//THIS COMPILES
        short z2 = (short) x + y;//THIS DOESN'T

How come the code snippet of z compiles, while z2 doesn't? When performing an arithmetic operation on short it will immediately promote it to a int. however I'm downcasting it back to short but it produces an error. Please explain. Am I missing anything?

user962206
  • 15,637
  • 61
  • 177
  • 270
  • First case you are downcasting the result of two integer additions, in the second case you are trying to assign an `int` + `short` to a `short` without casting. You're only casting the first argument to a `short`. – Kon May 08 '15 at 16:51
  • 1
    Check the answers to [this question](http://stackoverflow.com/questions/81392/java-why-do-i-receive-the-error-message-type-mismatch-cannot-convert-int-to-b). It applies to your case too. – Roberto Linares May 08 '15 at 16:52
  • `(short) x + y` is the same as `((int) (short) x) + (int) y` – Peter Lawrey May 08 '15 at 16:58
  • short z2 = (short) x + (short) y; //THIS also DOESN'T because of precendence. First '+' and than is casting to short. – Java bee Dec 31 '20 at 11:44
  • https://introcs.cs.princeton.edu/java/11precedence/ – Java bee Dec 31 '20 at 11:46

3 Answers3

3

This line:

(short) x + y

Can be understood like this:

short + int

Because the type cast only applies for x, not for the result of the sum. So, the result of the operation returns an int, thus the compiler exception.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

The second line compiles, because the result of the addition is casted to a short so it can be assigned to z, a short.

The third line doesn't compile, because the cast to short only applies to x, before the addition takes place. The result of the addition of a short and an int is an int, which can't be assigned directly to a short (z2).

The parentheses in the second line force the order of operations necessary for a short value to be assigned to a short variable.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • How is it being evaluated? is it being evaluated from left to right? not the operations first? – user962206 May 08 '15 at 16:54
  • The cast operator `()` has a higher [precedence](http://introcs.cs.princeton.edu/java/11precedence/) than the `+` operator, so the cast will operate first without parentheses. – rgettman May 08 '15 at 16:57
0

In the z you are casting the final outcome of x+y as a whole to a short and assigned it to a short.

But in the z2 you are casting x to a short and adding it with y gives a int. SO int can't be assigned to a short. That is why you get the compile error