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:
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: