Reputation: 377
By default, Java assumes you are defining an int value with a literal.
short x = 20; // There is an implicit conversion
But when we use "x" variable in an arithmetic expression, for eample:
short y = x * 2; //DOES NOT COMPILE
We know the result of 20 * 2 is 40, which can easily fit into a short variable. What is going on?
Upvotes: 1
Views: 166
Reputation: 3609
You can use the following notation using casting to assign the result of arithmetical operation to y
(if you do not want to make x
final
) :
short y = (short)(x * 2);
I think that the answer is in Java Language Specification. Look at point 4.2.2, There is a list of numerical operators that result in a value of type int or long and this is the reason why java treats it as int and casting is needed: https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.2.2
Upvotes: 0
Reputation: 617
I don't know the compiler implementation details. I guess the reason is that there is no way for the compiler to check because the value of x might not be known in compile time. So it could only assume it is an int. Else, how else do you expect the compiler to behave?
If you look at the * operator prototype, see: https://www.cs.cmu.edu/~pattis/15-1XX/15-200/lectures/voe/lecture.html
There is only one for (int, int), so technically there is not one for (short, short).
So then you might ask why does short x = 20 works? The reason is Java can only allow the auto casting to short if it's a constant, which "20" is a final in this case while x*2 is not a final See: Java - short and casting
Upvotes: 0
Reputation:
Because x
isn't final there is no guarantee that the variable will still be 20 when the programm reaches the point of:
short y = x * 2;
The compiler simply considers the possibility that your non-final variable x may have changed by that time (by whatever means) and therefor will not treat it simply as 20. If you define x as final the implicit conversation will work:
final short x = 20; // There is an implicit conversion
short y = x * 2; //DOES COMPILE
Upvotes: 6
Reputation: 802
When you write short x =20
then java compiles it successfully but when you write short y=x *2
then it will treated as int and you have to cast it to short like short y =(short)x*2
Upvotes: 0