What will be output of the following program code?
public class Test{
public static void main(String[] a){
short x = 10;
x = x*5;
System.out.print(x);
}
}
public class Test{
public static void main(String[] a){
short x = 10;
x = x*5;
System.out.print(x);
}
}
A. 50
B. 10
C. Compilation Error
D. None of these
Answer: Option C
Solution (By Examveda Team)
lossy conversion from int to shortx = x*5;
^
1 error
public class solution {
public static void main(String args[]){
short x = 10;
x = (short) (x*5);
System.out.print("x="+x);
}
}
but there is no compiler error when you change it to x *= 5. How is this possible?
ans- compilation error because of type promotion in expression all operand are promoted to higher range type available in expression and then operation is done here variable x is promoted to int type that's why it is not possible to store in short .to storing purpose casting is required.
short range is -32768 to 32767 ...then how x is int ...x=50 lies in the range ..so
how it is happening ....
here x is short...how it is converted to int ...
int isn't used anywhere how x is converted to short...x is already short.
x=x*5
x=50
but in the program x is short data type and 5 is int datatype
it is not possible to store int value in short so
ans Compile time error
5 is by default type int
if we use
x=x*(short)5;
then we get 50 answer
x=x*5;
here 5 is the integer , then it is not possible to get the result in short
it is issue with type. It should be type casted to short then ans is 50 (tested)
Whenever we perform arithmetic operation on integral data type(char, byte,short) then we have to store output in int.
No, it is not the issue of the range but type. Short is a smaller type as compared to int. and the 5 is interpreted as int. if you do
float x = 10.0f;
x = x * 1.4;
you will get the same error as the 1.4 is interpreted as double do it with
x = x * 1.4f and the problem solves.
As a whole, you can multiply a smaller type with a larger one
x*5 goes out of range for short. it comes in range of int. so error will come for possible lossy conversion of int to short.
Y the compilation errror? Plz can someone explain