Type casting | Core Java Forum
M
Mansoor Posted on 12/02/2020

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

 

According to me, the output should be 50 as the range for short is (-2^15 - 2^15-1) and 50 falls within that range.

But there is compilation error - 'Cannot convert int to short'

 

Please explain!!!


Y
Yogesh Chawla Replied on 12/02/2020

Because the default for numbers is Integer.

All you need to do is type casting

x = (short) (x * 5);

Try this. It will work.

Post the concepts of Generics, Type casting is also not required. Since we are dealing with small numbers over here, that's the reason, type casting is required.

 

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


M
Mansoor Replied on 12/02/2020

Do you mean to say, the default for mathematical operations on numbers is int? Because when I just use number and then display, the casting is not required.

 

Thanks for the quick reply!!


Y
Yogesh Chawla Replied on 12/02/2020

Yes.

Please read this as well.

 

There is a predefined implicit conversion from short to int, long, float, double, or decimal.

You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:

short x = 5, y = 12;

The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

short z = x + y;   // Error: no conversion from int to short

To fix this problem, use a cast:

short z = (short)(x + y);   // OK: explicit conversion

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

int m = x + y;
long n = x + y;