This happens because if we use wrapped primitive values like in the question (Integer
, Float
, Double
etc.) in a ternary operator, both values will be unboxed and coerced to a common type.
This may result in unexpected results as well.
In the first example, new Integer(12)
would be converted to a double
as it is the common type. Hence there are no compilation issue.
But in the second example both are Integer
which is not compatible with the left hand side type Double
.
Example taken from Sonar rule description S2154
:
Integer i = 123456789;
Float f = 1.0f;
// Assume condition = true
Number n = (condition) ? i : f; // i is coerced to float. n = 1.23456792E8
To fix this, we need to do explicit casting:
Integer i = 123456789;
Float f = 1.0f;
// Assume condition = true
Number n = condition ? (Number) i : f; // n = 123456789
Additional suggestion: Do not use new Double()
or new Integer()
etc. These constructors are deprecated. Instead use valueOf
method