Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated the references to Java 7 and changed to Applicability

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= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is 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
bgColor#ffcccc
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
bgColor#ccccff
byte[] b = new byte[4];
...
int result = 0;
for (int i = 0; i < 4; i++) 
  result = ((result << 8) | (b[i] & 0xff));

...

Code Block
bgColor#ccccff
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.

...

[Bloch 2005]

Puzzle 9: "Tweedledum"

 

Puzzle 31: "Ghost of Looper"

[Findbugs 2008]

"BIT: Bitwise OR of signed byte value"

[JLS 20052011]

§4.2.2, "Integer Operations"

 

§5.6, "Numeric Promotions"

 

§15.26.2, "Compound Assignment Operators"

...