wood burning stoves*
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
Author

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;
System.out.println(
(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
zarina
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: http://aspose.com/file-tools
 
subject: Why double not int
 
Similar Threads
ternary query
probem with comparable interface
ternary print Q
output
Unusual output