为什么Java中短整数除法的结果类型不是一个短整数? [英] Why is the resulting type of a division of short integers in Java not a short integer?

查看:85
本文介绍了为什么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,因此必须强制转换为short。

because the type of the expression i/j is apparently int, and hence must be cast to short.

为什么 i / j 的类型不短?

推荐答案

来自 Java规范


5.6.2二进制数字促销

5.6.2 Binary Numeric Promotion

当运算符将二进制数字提升应用于一对操作数时,每个操作数必须表示数值类型的值,以下规则依次使用扩展转换(第5.1.2节)进行转换必要时操作数:

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:

如果任一操作数的类型为double,则另一个操作数转换为double。

If either operand is of type double, the other is converted to double.

否则,如果任一操作数的类型为float,则另一个操作数转换为float。

Otherwise, if either operand is of type float, the other is converted to float.

否则,如果任一操作数的类型为long,则另一个操作数转换为lo ng。

Otherwise, if either operand is of type long, the other is converted to long.

否则,两个操作数都转换为int类型。

对于二进制运算,小整数类型被提升为 int ,操作结果为 int

For binary operations, small integer types are promoted to int and the result of the operation is int.

编辑:为什么会这样?简短的回答是Java从C复制了这种行为。更长的答案可能与所有现代机器至少进行32位本机计算这一事实有关,而且某些机器实际上可能更难做到8位和16位操作。

Why is it like that? The short answer is that Java copied this behavior from C. A longer answer might have to do with the fact that all modern machines do at least 32-bit native computations, and it might actually be harder for some machines to do 8-bit and 16-bit operations.

参见: C#中的OR-ing字节给出了int

这篇关于为什么Java中短整数除法的结果类型不是一个短整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆