加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:44:53 所属栏目: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 precisionfound : intrequired: short short k = i/j; 因
考虑这个代码:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读