考虑这段代码:
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,因此必须转换为 short。
为什么i/j
的类型不是short?
最佳答案
来自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 位 native 计算这一事实有关,而某些机器实际上可能更难进行 8 位和16 位操作。
关于java - 为什么 Java 中短整数除法的结果类型不是短整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2256864/