Java Math Operations – Why Disallow Int-to-Short Assignment?

data typesjavamath

In Java, the following code does not compile:

int val = 1;
short shortVal = val;  // Incompatible types

Anyone know why Java chooses to complain about this assignment, instead of simply truncating, when an integer × integer is also likely to overflow?

To illustrate:

int val = 46340;
int result = val * val;                    // 2147395600
System.out.println(result);
int overflowVal = 46341;
int result2 = overflowVal * overflowVal;   // -2147479015
System.out.println("Quietly overflowed: " + result2);

Best Answer

In the first case, the compiler knows that you're facing a potential loss of precision, so it can stop you. In the second case the overflow happens during a runtime calculation - though your example trivialy causes an overflow, there is no way for the compiler to check such occurrences in general case so it doesn't.