Reputation: 2871
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
Upvotes: 2
Views: 629
Reputation: 78003
Math.round
returns a long
, 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:
Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).
And from 5.6.2, binary numeric promotion:
If either operand is of type double, the other is converted to double.
And to illustrate the pitfalls with the conditional operator and for some fun, from Java puzzlers (puzzle 8):
char x = 'X';
int i = 0;
System.out.print(true ? x : 0); // prints X
System.out.print(false ? i : x); // prints 88 => (int)X
Also, check out the Hamlet and Elvis examples (video links).
Upvotes: 4
Reputation: 285405
The type returned from a ternary operator may be promoted so that the two potential return types match. This is called binary numeric promotion, and your variable is being promoted from long to double before conversion to a String.
If you had this where both potential return types are int or long:
double d = 10.1;
String rounded = (false ? 0 : Math.round(d)) + "";
What happens (not a rhetorical question since I'm no where near a Java compiler)?
Upvotes: 2