• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Jxam question

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What is the output of the following piece of code:
int x = 6;
double d = 7.7;
System.out.println((x > d) ? 99.9 : 9);
I thought the answer would be a 9. Instead the answer was 9.0.
Somebody please clarify .
Thanks
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In this code, the optional result values for the conditional operator, 99.99 (a double) and 9 (an int), are of different types. The result type of a conditional operator must be fully determined at compile time, and in this case the type chosen, using the rules of promotion for binary operands, is double. Because the result is a double, the output value is printed in a floating-point format.
The choice of which of the two values to output is made on the basis of the boolean value that precedes the ?. Since the test (x > d) is false. This causes the overall expression to take the second of the possible values, which is 9 rather than 99.99. Because the result type is promoted to a double, the output value is actually written as 9.0, rather than the more obvious 9.
If the two possible argument types had been entirely incompatible--for example, (x > d) ? "Hello" : 9--then the compiler would have issued an error at that line.
 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the answer is 9.0 then you can guess that the compiler is converting the two possible answers to doubles. The jls says that if one the second and third operands of the ?: operator is a double then numeric promotion is applied to the operands.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic