为什么Java中短整数除法的结果类型不是一个简单的整数?

前端之家收集整理的这篇文章主要介绍了为什么Java中短整数除法的结果类型不是一个简单的整数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑这个代码
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位操作.

参见:OR-ing bytes in C# gives int

原文链接:https://www.f2er.com/java/121394.html

猜你在找的Java相关文章