Question

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?

Était-ce utile?

La solution

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`

Autres conseils

The result of integer operations is either int or long. This is spelled out in the JLS:

4.2.2. Integer Operations

The numerical operators, which result in a value of type int or long:

  • The unary plus and minus operators + and - (§15.15.3, §15.15.4)

  • The multiplicative operators *, /, and % (§15.17)

  • The additive operators + and - (§15.18)

  • ...

Also:

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 that is convertible to a numeric type, the following rules apply, in order:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • 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.

...

Binary numeric promotion is performed on the operands of certain operators:

  • The multiplicative operators *, / and % (§15.17)

  • The addition and subtraction operators for numeric types + and - (§15.18.2)

  • The numerical comparison operators <, <=, >, and >= (§15.20.1)

  • The numerical equality operators == and != (§15.21.1)

  • The integer bitwise operators &, ^, and | (§15.22.1)

  • In certain cases, the conditional operator ? : (§15.25)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top