Reputation: 11
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?
Upvotes: 1
Views: 754
Reputation: 140318
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":
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)
)
Upvotes: 3
Reputation: 23
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)
Upvotes: 2