File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why double not int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why double not int" Watch "Why double not int" New topic

Why double not int

suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149
public class test {
public static void main(String args[]) {
int x = 4;
(x > 4) ? 99.99 :9));
Why the output is 9.0 as double why not 9 as integer.
zarina mohammad
Ranch Hand

Joined: Jun 26, 2002
Posts: 104
whats happening here is arthimetic promotion. the result is converted to the largest datatype which in this case is int to double
Soum Sark
Ranch Hand

Joined: May 31, 2002
Posts: 50
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
Paul Villangca
Ranch Hand

Joined: Jun 04, 2002
Posts: 133
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.
I agree. Here's the link:
subject: Why double not int
It's not a secret anymore!