You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

When using binary operators with operands of different types, be aware of the implicit casts.
In particular :

  1. If any of the operands is of a reference type, unboxing conversion is performed. Then:
  2. If either operand is of type double, the other is converted to double.
  3. Otherwise, if either operand is of type float, the other is converted to float.
  4. Otherwise, if either operand is of type long, the other is converted to long.
  5. Otherwise, both operands are converted to type int.

which means some errors could happen, especially if one of the operand is converted from a numeric type to double or float (see the INT33-J rule for more details regarding this issue).

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

In the following example,

int a = some_value;
double b = some_other_value;

double c = a + b;

a is converted to double before the {+} operator is applied.

A more complex example :

int a = some_value;
char b = some_character;

if( (a + b) == 0.0f){
    //do something
}

this time, b is first converted to int, then, the {+} operator is applied. The result of (a+b) is then converted to float, and the comparison operator is finally applied.

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.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP06-J

medium

probable

medium

P8

L2

Bibliography

Java specification : "http://java.sun.com/docs/books/jls/third_edition/html/conversions.html".

  • No labels