ExamVeda
Login
Home
Data Types and Variables
?

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);
	}  
}

Answer & Solution
Correct Answer: Option C
lossy conversion from int to short
x = x*5;
       ^
1 error
Examveda
Question posted by Examveda
Community

Join the Discussion

14 Comments
Princy Shreya
Princy Shreya 3 years ago
public class solution {
public static void main(String args[]){
short x = 10;
x = (short) (x*5);
System.out.print("x="+x);
}
}
Vaalarivan P
Vaalarivan P 4 years ago
but there is no compiler error when you change it to x *= 5. How is this possible?
Rakesh Sharma
Rakesh Sharma 7 years ago
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.
Ankit Mondal
Ankit Mondal 8 years ago
short range is -32768 to 32767 ...then how x is int ...x=50 lies in the range ..so
how it is happening ....
Ankit Mondal
Ankit Mondal 8 years ago
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.
Ch Siva
Ch Siva 8 years ago
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
Priyabrata Biswal
Priyabrata Biswal 8 years ago
5 is by default type int
Aditya Sahai
Aditya Sahai 9 years ago
if we use
x=x*(short)5;
then we get 50 answer
Aditya Sahai
Aditya Sahai 9 years ago
x=x*5;
here 5 is the integer , then it is not possible to get the result in short
Saketh Saraswathi
Saketh Saraswathi 9 years ago
it is issue with type. It should be type casted to short then ans is 50 (tested)
Dishant Jain
Dishant Jain 10 years ago
Whenever we perform arithmetic operation on integral data type(char, byte,short) then we have to store output in int.
Abhishek Bera
Abhishek Bera 10 years ago
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
Gurjot Kaur
Gurjot Kaur 10 years ago
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.
Sushmita Dalai
Sushmita Dalai 10 years ago
Y the compilation errror? Plz can someone explain