Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional if-else statement in java [duplicate]

I am unable to understand how the below code print 50.0

public class Pre
{
    public static void main(String[] args)
    {
        int x=10;
        System.out.println((x > 10) ? 50.0 : 50); //output 50.0
    }
} 

It should print 50 (I guess) not 50.0

Isn't the above code is equivalent to below code?,

public class Pre
{
    public static void main(String[] args)
    {
        int x=10;
        if(x>10)
            System.out.println(50.0);
        else
            System.out.println(50);//output
    }
}

If they are equivalent,then why the difference in output ?

like image 968
Frosted Cupcake Avatar asked Jul 06 '15 15:07

Frosted Cupcake


3 Answers

Java ensure your types are coherent, so in the first statement

(x > 10) ? 50.0 : 50

You have a double first, so the return type of the expression is double, and the litteral int is converted to double. Hence the two sides of the conditional are the same!

If you change it to

System.out.println((x > 10) ? 50.0 : 49);

It prints 49.0.

the if/else is not an expression, hence it doesn't have to do any conversion.

like image 138
JP Moresmau Avatar answered Oct 22 '22 09:10

JP Moresmau


It's printing 50.0 because in the first case you are calling the OutputStream.println(double) method, because your first expression returns a double irrespective of your condition.

But in the second case you are calling OutputStream.println(int) method.

like image 6
Codebender Avatar answered Oct 22 '22 08:10

Codebender


The type of the ternary conditional operator - (x > 10) ? 50.0 : 50) is determined by both the 2nd and 3rd operands. In your case, it must be able to contain the values of both 50.0 and 50, so its type is double.

Therefore, even when the expression returns 50, it is cast to double, and you see 50.0.

If you change

System.out.println((x > 10) ? 50.0 : 50);

to

System.out.println((x > 10) ? 50.0 : 10);

You'll see 10.0 printed, which will make it obvious that the correct value (the right side of the :) is returned.

like image 5
Eran Avatar answered Oct 22 '22 09:10

Eran