最近我注意到了Java在基本算术运算上的一些特殊情况。以下是代码:
byte a = 3;
byte b = 4;
byte c = a * b;
我遇到了一个 "type mismatch" 编译错误...
在Java中,基本算术运算(+
, -
, *
, /
)只针对于原始数据类型如int
和更高级别的类型(如long
,double
等)进行操作,而对于byte
和 short
等类型进行算术运算时会先转换为int
然后再进行计算吗?
最近我注意到了Java在基本算术运算上的一些特殊情况。以下是代码:
byte a = 3;
byte b = 4;
byte c = a * b;
我遇到了一个 "type mismatch" 编译错误...
在Java中,基本算术运算(+
, -
, *
, /
)只针对于原始数据类型如int
和更高级别的类型(如long
,double
等)进行操作,而对于byte
和 short
等类型进行算术运算时会先转换为int
然后再进行计算吗?
byte
、char
和 short
的操作会被扩展为 int
,除非编译器能够确定值的范围。
final byte a = 3, b = 4;
byte c = a * b; // compiles
final byte a = 3, b = 40;
byte c = a * b; // compiles
final int a = 3, b = 4;
byte c = a * b; // compiles !!
byte a = 3, b = 4;
byte c = a * b; // doesn't compile as the result of this will be `int` at runtime.
final byte a = 30, b = 40;
byte c = a * b; // doesn't compile as the value is too large, will be an `int`
final int a = 300000, b = 400000;
int c = a * b; // compiles but overflows, is not made a `long`
final
会有这么大的区别。但是无论如何,看起来很奇怪,因为即使在第二个例子中,a
和 b
仍然被声明为字节... - fgeint
或者 long
。这在JLS中有明确说明:
4.2.2. 整数运算
数字运算符,其结果为类型 int
或 long
: