jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Unusual output 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 "Unusual output" Watch "Unusual output" New topic

Unusual output

Bonny Sen

Joined: May 09, 2006
Posts: 26
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));

With Love, Bonny
"Life is like an ice-cream, Enjoy it before it melts..."
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
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

Joined: Apr 25, 2005
Posts: 809
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

[ June 17, 2006: Message edited by: Naseem Khan ]

Asking Smart Questions FAQ - How To Put Your Code In Code Tags
Bonny Sen

Joined: May 09, 2006
Posts: 26
Thank you so much, especially for the Link on ?: operator.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
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
subject: Unusual output
It's not a secret anymore!