'error: incompatible types: possible lossy conversion from int to short

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

This is my problem and below is the error I got.

Solution.java:7: error: incompatible types: possible lossy conversion from int to short
x =  x * 5;
^
1 error

How is this conversion from int to short?



Solution 1:[1]

The 5 is explicitly an integer. Thus, by multiplying an int with a short, you will have an int. You can try to convert with (short)

Solution 2:[2]

When you multiply two numbers together, they undergo binary numeric promotion, which is just a term used to mean "convert them to a common type so they can be multiplied":

  • If one number is a double, the other is converted to a double
  • Otherwise, if one number is a float, the other is converted to a float
  • Otherwise, if one number is a long, the other is converted to a long
  • Otherwise, both numbers are converted to ints.

And the result of multiplying those converted values is the type of the converted values, e.g. int times double => convert int to double => result is a double.

Notice that this doesn't go any further than int: if you multiply a byte by a byte, or a short by a byte, or a short by an int, both of those numbers are widened to int; and the result is an int.

Hence, short times int is an int.

You can either explicitly cast back to a short:

x = (short) (x * 5);

Or use compound assignment, which implicitly casts:

x *= 5;

(a OP= B is roughly the same as a = (type of a) (a OP b))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alan bretelle atomic85340
Solution 2 Andy Turner