Versions Compared

Key

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

...

These conversions can happen with the following operators : multiplicative operators (%, *, /), additive opeators (+, -) comparisons (<, >, <=, >=) and equality (==, !=) operators and the integer bitwise operators (&, |, ^) and can be particularly harmful in the case of a conversion from an integral type to a floating point type (see INT33-J for more details), due to widening conversion.

Examples

In the following example,

...

Code Block
class Test{
  public static void main(String[] args){
    int big = 1999999999;
    double big_float = big;
    float one = 1.0f;
    System.out.println(big*one);
    System.out.println(big_float);
  }
}

The output is
2.0E9
1.999999999E9
while the expected output is :
2.0E9
2.0E9.
big is first converted to a float, and loses some precision, which explains the 2.0E9. However, big_float doesn't lose any precision since it's a wider type than float, this is why the two output are different.

...

the output is what is expected :
1.999999999E9
1.999999999E9,
because this time, one is a double and doesn't lose precision.

Note : these output were generated on a Java Hotspot(TM) 64-bit server VM (version 1.5.0), and compiled with javac, version 1.5.0.

Risk assessment

If an operator is applied and some unexpected conversion occur, the result may be different from what the programmer and lead to some unexpected behavior and ultimately to a flaw or an abnormal termination.

...