Conditional if else statements in Java

See English answers > why does the internal operator unexpectedly cast integers? two

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

Is the code above equal to the code below?

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, why the output difference?

Solution

Java ensures that your types are consistent, so in the first statement

(x > 10) ? 50.0 : 50

You have a double, so the return type of the expression is double, and literal int is converted to double So the conditional two sides are the same!

If you change it

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

It prints 49.0

If / else is not an expression, so it does not need any conversion

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>