【发布时间】:2016-12-08 08:03:32
【问题描述】:
在 Java 中,如果我们将bytes、shorts 或ints 相除,我们总是得到int。如果其中一个操作数是long,我们将得到long。
我的问题是 - 为什么 byte 或 short 除法不会导致 byte 或 short?为什么总是int?
显然,我不是在寻找“因为 JLS 这么说”的答案,而是在询问 Java 语言中此设计决策的技术原理。
考虑这个代码示例:
byte byteA = 127;
byte byteB = -128;
short shortA = 32767;
short shortB = -32768;
int intA = 2147483647;
int intB = - -2147483648;
long longA = 9223372036854775807L;
long longB = -9223372036854775808L;
int byteAByteB = byteA/byteB;
int byteAShortB = byteA/shortB;
int byteAIntB = byteA/intB;
long byteALongB = byteA/longB;
int shortAByteB = shortA/byteB;
int shortAShortB = shortA/shortB;
int shortAIntB = shortA/intB;
long shortALongB = shortA/longB;
int intAByteB = intA/byteB;
int intAShortB = intA/shortB;
int intAIntB = intA/intB;
long intALongB = intA/longB;
long longAByteB = longA/byteB;
long longAShortB = longA/shortB;
long longAIntB = longA/intB;
long longALongB = longA/longB;
byteA 除以byteB 只能是一个字节,不是吗?
那么为什么byteAByteB 必须是int?为什么shortALongB 不能是short?
为什么intALongB 必须是long,结果总是适合int,不是吗?
更新
正如@Eran 指出的那样,(byte)-128/(byte)-1 导致128 不适合byte。但是那为什么不short呢?
更新 2
接下来,正如@Eran(再次)指出的那样,(int) -2147483648 / (int) -1 也不适合int,但结果仍然是int,而不是long。
【问题讨论】:
-
理由不是技术性的,我很确定。
-
该规则在任何类 C 语言中都是相同的。此外,JVM 是用 C 和 C++ 编写的,因此它遵循相同的规则Why are integer types promoted during addition in C?
标签: java integer division integer-division