Java Ternary operator outputs different result than if else statement

mmz :

I'm writing a program that takes a number and removes the trailing zeros if the number is an integer. I am using the ternary operator but it doesn't work as expected. But if I write it as a if else statement it works.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double number = scanner.nextDouble();
        System.out.println(((int)number == (double)number) ? (int)number : number); // Always outputs a double

        if ((int)number == (double)number) { // Outputs correct result
            System.out.println((int)number);
        }
        else {
            System.out.println(number);
        }
    }

}

For example if I input 5 i get

5.0
5

if I input 7.3 I get

7.3
7.3

So it seems that it works for the if else statement but not the ternary operator.

Jon Skeet :

In your if/else statement, you're calling PrintStream.println(int) or PrintStream.println(double) depending on which branch you're taking.

With the conditional operator ?: you're always calling PrintStream.println(double), because that's the type of the ?: expression. When the second and third operands of the ?: operator have different types, the compiler picks the overall type of the expression according to the rules of JLS 15.25 and performs appropriate conversions where necessary.

In this case, the overall type is double, so it's as if you're writing:

double tmp = ((int) number == (double)number) ? (int)number : number;
System.out.println(tmp);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19061&siteId=1