This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why double not int

 
suresh kamsa
Ranch Hand
Posts: 149
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 104
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic