>
>
>
V6106. Casting expression to 'X' type b…


V6106. Casting expression to 'X' type before implicitly casting it to other type may be excessive or incorrect.

The analyzer found that after an explicit conversion of a variable to one numeric data type, a further implicit conversion to another numeric data type is performed. This usually indicates that an explicit conversion is either made mistakenly or unnecessary.

There are several types of conversion over numeric types in Java:

  • In widening (implicit) conversions, a smaller data type is assigned to a larger type, for example: byte -> short -> int -> long -> float -> double. Those are safe since they do not lead to data loss after the conversion. The compiler performs them silently and does not issue warnings.
  • In narrowing (explicit) conversions, a larger data type needs to be assigned to a smaller data type. In such cases, there is a risk of losing data, so explicit type conversion is always done manually, under the responsibility of the programmer.

When a sequence of explicit and implicit transformations occurs in the same context, it's a reason to take a closer look at the code.

Let's consider an example of a suspicious type conversion that occurred in one of the existing projects:

public void method(...., Object keyPattern, ....)
{
  ....
  if (keyPattern instanceof Integer)
  {
    int intValue = (Integer) keyPattern;
    ....
  }
  else if (keyPattern instanceof Short)
  {
    int shortValue = (Short) keyPattern;
    ....
  }
  ....
}

After the 'keyPattern instanceof Short' check, the 'keyPattern' variable is explicitly cast to the 'Short' type. But when assigning a value to the 'shortValue' variable, an implicit casting of the previously made cast to the 'int' type takes place, since the 'shortValue' variable is of type 'int'. The Java compiler does not issue warnings here, since both conversions are valid. The programmer most likely wanted to specify the 'short' type for the 'shortValue' variable.

The corrected version of the code should look like this:

public void method(...., Object keyPattern, ....)
{
  ....
  if (keyPattern instanceof Integer)
  {
    int intValue = (Integer) keyPattern;
    ....
  }
  else if (keyPattern instanceof Short)
  {
    short shortValue = (Short) keyPattern;
    ....
  }
  ....
}

This diagnostic is classified as: