1

I have encountered an interesting problem when Java programming. I do not recall that I had such a problem previously. I declared two variables. Type of x is byte and y is short. Summation of x and 5 cannot be assigned to y.

    byte x = 3;
    short y = 103;
    y = x + 5;

NetBeans gives possible lossy conversion from int to short error. However, there is no problem with y = 5. I also tried y = x + (short)5. But this doesn't work either. Only y = (short)(x + 5)works. Moreover, y = x + xdoesn't work. It is weird. Does Java compiler automatically convert result of any calculation to int?

user2972185
  • 231
  • 3
  • 12
  • Did you try `y = (short)x + 5`? – DigitalNinja Apr 18 '15 at 00:36
  • Short answer: yes, any arithmetic operation on bytes or shorts will be promoted to an int result. See the linked question for details. – Louis Wasserman Apr 18 '15 at 00:38
  • Java should convert everything to the largest operand type so of short and int is largest. So `x + 5` is int. I think the compiler is happy to do the conversion from the literal 103 to a short but not a variable. The fix would be to change the calculation to `x + (short)5` – redge Apr 18 '15 at 00:42

0 Answers0