I’m wondering why there is an inconsistency with the code below. I would expect the same output, but when using the inline conditional statement, it appends a .0 to the string.
Do I have some error in my code?
double d = 10.1;
String rounded = (false ? d : Math.round(d)) + "";
System.out.println(rounded);//10.0
rounded = Math.round(d) + "";
System.out.println(rounded);//10
Math.roundreturns along, therefore the two operands of the conditional operator do not have the same type, and thus a more complex rule is followed to determine the type of the overall operation, as defined in JLS §15.25:And from 5.6.2, binary numeric promotion:
And to illustrate the pitfalls with the conditional operator and for some fun, from Java puzzlers (puzzle 8):
Also, check out the Hamlet and Elvis examples (video links).