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

Unusual output

 
Bonny Sen
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output of the code below is 9.0
Can someone explain why?

public class Trials {
public static void main(String args[]) {
int x = 4;
System.out.println(((x > 4) ? 99.99 : 9));
}
}
 
wise owen
Ranch Hand
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
15.25 Conditional Operator ? : in Java Language Specification:

Otherwise, binary numeric promotion (�5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (�5.1.8) and value set conversion (�5.1.13).


5.6.2 Binary Numeric Promotion:

if either operand is of type float, the other is converted to float.
 
Naseem Khan
Ranch Hand
Posts: 809
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See how ternary operators work?




if someboolean is true, value of x will be assigned to z. z become 8

if someboolean is false, then value of y will be assigned to z. z become 9.

In your code, x > 4 is false, so output is 9.0 (9 gets promoted to double). If x is suppose 5. then x > 4 will be true and then you will get output 99.99


Naseem
[ June 17, 2006: Message edited by: Naseem Khan ]
 
Bonny Sen
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much, especially for the Link on ?: operator.
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Bonny-

On your way in you may have missed that we have a policy on screen names here at JavaRanch. Basically, it must consist of a first name, a space, and a last name. Since yours does not conform with it, please take a moment to change it, which you can do right here.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic