考虑这个代码:
public class ShortDivision { public static void main(String[] args) { short i = 2; short j = 1; short k = i/j; } }
编译这会导致错误
ShortDivision.java:5: possible loss of precision found : int required: short short k = i/j;
因为表达式i / j的类型显然是int,因此必须被简化.
为什么i / j的类型不短?
解决方法
从
Java spec:
5.6.2 Binary Numeric Promotion
When an operator applies binary numeric promotion to a pair of operands,each of which must denote a value of a numeric type,the following rules apply,in order,using widening conversion (§5.1.2) to convert operands as necessary:
If either operand is of type double,the other is converted to double.
Otherwise,if either operand is of type float,the other is converted to float.
Otherwise,if either operand is of type long,the other is converted to long.
Otherwise,both operands are converted to type int.
对于二进制操作,小整数类型被提升为int,操作结果为int.
编辑:为什么这样呢?简单的答案是Java将这个行为从C复制了一个更长的答案可能与所有现代机器至少进行32位本地计算的事实有关,一些机器可能实际上更难做到8位,16位操作.