Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

...

These conversions can happen with the following operators : multiplicative operators (%, *, /), additive operators (+, -), comparison operators (<, >, <=, >=) and , equality operators (==, !=) and the integer bitwise operators (&, |, ^).

...

In this noncompliant code example, the statement big * one carries out a binary operation. As big is an of type int and one is of type float, big is promoted to a the type float. This implicit cast results in loss of precision.

Code Block
bgColor#ffcccc
class Test{
  public static void main(String[] args){
    int big = 1999999999;
    float one = 1.0f;
    // binary operation, loses precision duebecause toof implicit cast
    System.out.println(big * one); 
  }
}

The output produced is This code outputs 2.0E9 whereas, the expected output is 1.999999999E9.

Compliant Solution

In this case, a double should be used This compliant solution uses the double type instead of a float for a safe as a safer means of handling the widening primitive conversion caused by resulting from integer promotion.

Code Block
bgColor#ccccff
class Test{
  public static void main(String[] args){
    int big = 1999999999;
    double one = 1.0d; // double instead of float
    System.out.println(big*one);
  }
}

...

Wiki Markup
This noncompliant code example shows integer promotion when resulting from the use of the bit-wise OR operator is used. The byte array element is sign extended to 32 bits before it is used as an operand. If it contained the value {{0xff}}, now it would contain {{0xffffffff}} \[[Findbugs 08|AA. Java References#Findbugs 08]\].  

...