Unexpected type resulting from the ternary operator

You’re seeing an effect similar to the one in this question.

Slightly different rules govern the way Java handles types with the ternary operator than with an if statement.

Specifically, the standard says:

The type of a conditional expression is determined as follows:

Otherwise, if the second and third operands have types that are
convertible (§5.1.8) to numeric types, then there are several cases:

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.

Flipping to that page of the standard, we see:

If either operand is of type double, the other is converted to double.

which is what’s happening here, followed by autoboxing to a Double. It appears that no such conversion happens with the if statement, explaining the difference.

More broadly — this isn’t a very good idea. I don’t think it’s good design to return one of an int or a double depending on the value — if you want to round something off, use Math.floor, and if you don’t want decimals printed, use printf.

EDIT: I don’t think it’s a good idea to do hacky things to circumvent the regular numeric conversion system. Here’s an idea that gives you a String directly, which appears to be what you want:

static String convert3(double d) {
    return ((d % 1 == 0) ? Integer.toString((int)d) : Double.toString(d));
}

Leave a Comment