Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. When using arithmetic operators with mixed operand sizes, narrower operands are promoted to the type of the wider operand.
Promotion Rules
The Java Language Specification (JLS) [JLS 2011], §5.6, "Numeric Promotions", " describes numeric promotion as the following:
...
Type coercion may occur when compound expressions are used with mixed operand types. Examples of compound assignment operators are +=, -=, *=, /=, &=, ^=, %=, <<=, >>=, >>>= and |=.
According to the JLS §15.26.2, "Compound Assignment Operators","
A compound assignment expression of the form
E1 op= E2is equivalent toE1 = (T)((E1) op (E2)), whereTis the type ofE1, except thatE1is evaluated only once.
...
This noncompliant code example shows integer promotion resulting from the use of the bit-wise OR operator. The byte array element is sign-extended to 32 bits before it is used as an operand. If it originally contained the value 0xff, it would contain 0xffffffff [Findbugs 2008].
| Code Block | ||
|---|---|---|
| ||
byte[] b = new byte[4];
...
int result = 0;
for (int i = 0; i < 4; i++)
result = ((result << 8) | b[i]);
|
...
This compliant solution masks off the upper 24 bits of the byte array element to achieve the intended result.
| Code Block | ||
|---|---|---|
| ||
byte[] b = new byte[4];
...
int result = 0;
for (int i = 0; i < 4; i++)
result = ((result << 8) | (b[i] & 0xff));
|
...
| Code Block | ||
|---|---|---|
| ||
int i = -1; i >>>= 1; |
...
Applicability
Failing to consider integer promotions when dealing with floating-point and integer operands can result in loss of precision.
...
Puzzle 9: "Tweedledum" | |
| Puzzle 31: "Ghost of Looper" |
"BIT: Bitwise OR of signed byte value" | |
| |
|
...