Have a look to the following java expression:
srcVariableValue =
((leftRealValue instanceof Integer) ? ((Integer) leftRealValue) : ((Double) leftRealValue))
+
((rightRealValue instanceof Integer) ? ((Integer) rightRealValue) : ((Double) rightRealValue));
When it is executed, if leftRealValue and rightRealValue are Integer, the result is Double.
For instance:
- rightRealValue = 1 type Integer
- leftRealValue = 0 type Integer
Result:
- srcVariableValue = 1.0 type Double
Is this the expected behaviour? Of course, switching to if statement, it works well, the result is of type Integer.
I’m using Java 7
Thanks so much.
Advertisement
Answer
For both primitive operands (int, double) and wrapper class operands (Integer, Double) binary numeric promotion will be applied.
bnp(int,double) bnp(Integer,Double)
It means, first, for the second scenario, an unboxing conversion happens.
Integer -> int Double -> double
Then, for both, a widening primitive conversion takes place resulting in a double
double int -> double double = expression ? double : double
which may be converted further based on the variable you assign the result to.