我最近注意到 Java 关于 Java 中基本算术运算的特性。用下面的代码
byte a = 3;
byte b = 4;
byte c = a * b;
我收到“类型不匹配”编译错误...
Java中的基本算术运算(+
、-
、*
、/
)只对primitive进行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`
关于java - int 的基本算术运算 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125843/