0

For this code:

  public class Solution{
       public static void main(String[] args){
                     short x = 10;
                     x =  x * 5;
                     System.out.print(x);
       }
    }

This will give compile error - “Lossy conversion from int to short”

Why? Short has a maximum value of 32,767, 10 * 5 = 50, so why am I getting this error?

  • I did add the tag, it went, had to add it again. So why is 5 an int and not a short? I mean, 5 can also be a short. Or does the compiler just assume its an int? @KenWhite – futuredeveloper Apr 06 '22 at 01:07
  • 3
    Does this answer your question? [Increment char variable by an int value](https://stackoverflow.com/questions/35374896/increment-char-variable-by-an-int-value) – phuclv Apr 06 '22 at 01:08
  • a literal is int by default if it's in int's range, and operations are int-promoted. It's the same as other C-like languages. Duplicates: [incompatible types: possible lossy conversion from int to byte error?](https://stackoverflow.com/q/55322896/995714), [Inconsistent "possible lossy conversion from int to byte" compile-time error](https://stackoverflow.com/q/56162939/995714), [Subtract int from char : possible lossy conversion int to char](https://stackoverflow.com/q/40534091/995714) – phuclv Apr 06 '22 at 01:12
  • Only int, long, float, and double values may be multiplied. `x * 5` forces `x` to be an int, and the result is an int. The compiler only compiles code; it doesn’t run the code and it doesn’t have the ability to keep track of the value of `x` in a program, so it doesn’t know that `x` will be 10 when that line executes. – VGR Apr 06 '22 at 01:27
  • It'll work if you do `x *= 5` – shmosel Apr 06 '22 at 01:34

1 Answers1

1

When you do calculations with short, byte or char Java automatically converts them to int and return int result so you should has to use casting. x = (short) (x*5)

Erhan Kilic
  • 33
  • 10