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 ?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With