I recently noticed an idiosyncrasy of Java regarding basic arithmetic operations in Java. With the following code
byte a = 3;
byte b = 4;
byte c = a * b;
I get a "type mismatch" compilation error...
Are basic arithmetic operations in Java (+, -, *, /) only performed on primitive data types of int and higher order (long, double, etc.), whereas arithmetic operations on byte and short are first cast to int and then evaluated?
解决方案
Operations on byte, char and short are widened to int unless the compiler can determine the value is in range.
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 !!
but
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`
BTW This compiles even though it results in an overflow. :]
final int a = 300000, b = 400000;
int c = a * b; // compiles but overflows, is not made a `long`