java - 为什么 Java 中短整数除法的结果类型不是短整数?

标签 java syntax

考虑这段代码:

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 位操作。

另请参阅:OR-ing bytes in C# gives int

关于java - 为什么 Java 中短整数除法的结果类型不是短整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2256864/

相关文章:

java - Log4j/Slf4j 记录到 BigQuery

java - Springboot连接RDS抛出异常 "Caused by: java.security.cert.CertificateExpiredException: NotAfter: Fri Mar 06 00:54:04 EAT 2020"

c++ - int a[] = {1,2,};为什么允许在初始化列表中使用尾随逗号?

c# - .( 在 C# 或 VB.Net 中合法吗?

java - OpenCV改变矩形中的RGB参数

java - 开始新 Activity android后访问 Intent

css - 在哪里可以找到 Neo4j GRASS 语言的语法概述?

c++ - C++中访问另一个类的方法

java - Reactor中的doAfterSucces和doOnSuccess有什么区别?

c - 指向函数返回的指针