I have seen it discussed somewhere that the following code results in obj
being a Double
, but that it prints 200.0
from the left hand side.
Object obj = true ? new Integer(200) : new Double(0.0);
System.out.println(obj);
Result: 200.0
However, if you put a different object in the right hand side, e.g. BigDecimal
, the type of obj
is Integer
as it should be.
Object obj = true ? new Integer(200) : new BigDecimal(0.0);
System.out.println(obj);
Result: 200
I presume that the reason for this is something to do with casting the left hand side to a double
in the same way that it happens for integer
/double
comparisons and calculations, but here the left and right sides do not interact in this way.
Why does this happen?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…