简体   繁体   中英

I don't understand why I get the compiler error "Lossy conversion from int to short"

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM