What data types will automatically be given the following expressions (byte * byte) and (short * short)
2 answers
Expressions will be cast to int .
The JLS states that in the case of a series of operations (*, /,%,! =, Etc.) with 2 numeric operands, the coercion of types with an extension will be performed.
5.6.2. Binary Numeric Promotion
The following rules apply, in the following rules apply, in order:
- This is a reference to unboxing conversion (§5.1.8).
- Widening primitive conversion (§5.1.2) is the following rules:
- If either is converted to double.
- Otherwise, if either is converted to float.
- Otherwise, if either the operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
After the type conversion, if any, value set conversion (§5.1.13) is applied to each operand.
Thus, unboxing first occurs, and then the casting of the operands to int . The operations to which it applies:
Binary numeric promotion 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)
Well, the very casting with the extension:
5.1.2. Widening Primitive Conversion
19 specific conversions are called the widening primitive conversions:
- byte to short, int, long, float, or double
- short to int, long, float, or double
- char to int, long, float, or double
- int to long, float, or double
- long to float or double
- float to double
If I am not mistaken, the data types byte and short will be reduced to the type int when performing the multiplication operation.