Forums Register Login

Why double not int

+Pie Number of slices to send: Send
public class test {
public static void main(String args[]) {
int x = 4;
System.out.println(
(x > 4) ? 99.99 :9));
}
}
Why the output is 9.0 as double why not 9 as integer.
+Pie Number of slices to send: Send
whats happening here is arthimetic promotion. the result is converted to the largest datatype which in this case is int to double
zarina
+Pie Number of slices to send: Send
the ternary operator works when both sides of : are compatible with each other. So in order to make it compatible the java compiler promotes 9 to 9.0 to make it double and so the result is 9.0 . You would get the answer as 9 if 99.99 was 99 since in that case there is no promotion done
+Pie Number of slices to send: Send
The compiler has to determine at compile-time the result type of the ternary operation. It does this by looking at both possible results for the operation, and since there's a double, the result should be a double.
eat bricks! HA! And here's another one! And a tiny ad!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 745 times.
Similar Threads
ternary query
probem with comparable interface
ternary print Q
Unusual output
output
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:53:16.