0

While I have been studying for my OCA exam I came across something in Java that got me thinking "Why is this acceptable?".

This is not acceptable for the compiler.

short shortX = 1;
short shortY = 1;
short shortZ = shortX + shortY; //Compiler error

Although this is.

short shortZ = (short)1 + (short)1;

To me, they both seem exactly the same. My theory is that shortX and shortY are literals defined as an int just stored in a short variable, while casting directly tells the compiler the literal is a short, making it acceptable.

I would understand if the equation result was casted but it isn't, just the literals are. Does anyone have some clarification to soothe my inner curiosity?

1 Answers1

0

Here any direct arithmetic summation of variable will result in integer because compiler will not be 100% sure that it will fit in short size because variable assignment will be done at run times so it will not allowed you to assign to your short variable so your first case will give compilation error, while in your second case you are directly using 1 which is like fixed and sure to have range of short , so even if you not cast it will work fine

Jekin Kalariya
  • 3,475
  • 2
  • 20
  • 32