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

Compare with Current View Page History

« Previous Version 7 Next »

We using binary operators, be aware that some of the operands may be promoted to a wider type, to match the type of the other operand. For example in the expression 'a' == 42, the 'a' will be promoted to an int before the comparison is carried out.

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), which means you should pay special attention to the bullets two and three in the previous list.

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.

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

EXP07-J

low

probable

medium

P4

L3

References

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

  • No labels