Numeric Promotion Context
Numeric operators allow only operands of certain types. Numeric promotion results in conversions being applied to the operands to convert them to permissible types. Numeric promotion conversions that can occur in a numeric promotion context are shown in the fifth column of Table 2.17. Permissible conversion categories are widening primitive conversions and unboxing conversions. A distinction is made between unary and binary numeric promotion.
Unary Numeric Promotion
Unary numeric promotion proceeds as follows:
- If the single operand is of type Byte, Short, Character, or Integer, it is unboxed. If the resulting value is narrower than int, it is promoted to a value of type int by a widening conversion.
- Otherwise, if the single operand is of type Long, Float, or Double, it is unboxed.
- Otherwise, if the single operand is of a type narrower than int, its value is promoted to a value of type int by a widening conversion.
- Otherwise, the operand remains unchanged.
In other words, unary numeric promotion results in an operand value that is either int or wider.
Unary numeric promotion is applied in the following expressions:
- Operand of the unary arithmetic operators + and – (p. 58)
- Array creation expression; for example, new int[20], where the dimension expression (in this case, 20) must evaluate to an int value (§3.9, p. 117)
- Indexing array elements; for example, objArray[‘a’], where the index expression (in this case, ‘a’) must evaluate to an int value (§3.9, p. 120)
Binary Numeric Promotion
Binary numeric promotion implicitly applies appropriate widening primitive conversions so that the widest numeric type of a pair of operands is always at least int. If T is the widest numeric type of two operands after any unboxing conversions have been performed, the operands are promoted as follows during binary numeric promotion:
If T is wider than int, both operands are converted to T; otherwise, both operands are converted to int.
This means that the resulting type of the operands is at least int.
Binary numeric promotion is applied in the following expressions: