Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

if statement - "Wrong" return type when using if vs. ternary opertator in Java

In the following class, the return type of the two methods is inconsistent with the idea that the ternary operator:

return condition?a:b;

is equivalent to

if(condition) {
    return a;
} else{ 
    return b;
}

The first returns a Double and the second a Long:

public class IfTest {
    public static Long longValue = 1l;
    public static Double doubleValue = null;

    public static void main(String[] args) {
        System.out.println(getWithIf().getClass());// outpus Long
        System.out.println(getWithQuestionMark().getClass());// outputs Double
    }

    public static Object getWithQuestionMark() {
        return doubleValue == null ? longValue : doubleValue;
    }

    public static Object getWithIf() {
        if (doubleValue == null) {
            return longValue;
         } else {
            return doubleValue;
        }
    }
}

I can imagine this has to do with the compiler narrow casting the return type of getWithQuestionMark() but is that language wise ok? It's certainly not what I would have expected.

Any insights most welcome!

Edit: there's very good answers below. Additionally, the following question referenced by @sakthisundar explores another side effect of the type promotion occurring in the ternary operator: Tricky ternary operator in Java - autoboxing

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Basically it's following the rules of section 15.25 of the JLS, specifically:

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.

So section 5.6.2 is followed, which will basically involves unboxing - so this makes your expression work as if longValue and doubleValue were of types long and double respectively, and the widening promotion is applied to the long to get an overall result type of double.

That double is then boxed in order to return an Object from the method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...