Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why double not int

 
suresh kamsa
Ranch Hand
Posts: 149
  • 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
  • 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
  • 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
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic