开发者

Missing Java error on conditional expression?

With methods test1() and test2(), I get a Type Mismatch Error: Cannot convert from null to int, which is correct; but why am I not getting the same in method test3()? How does Java evaluate the conditional expression differently in that case? (obviously, a NullPointerException will rise at runtime). Is it a missing error?

public class Test {

    public int test1(int param) {
        return null;
    }

    public int test2(int param) {
        if (param > 0)
   开发者_如何学C         return param;
        return null;
    }

    public int test3(int param) {
        return (param > 0 ? param : null);
    }

}

Thanks in advance!


The conditional operator is quite tricky when you mix the type of the operators; it's the subject of many Java Puzzlers.

Here's a classic example:

System.out.println(true ? Integer.valueOf(1) : Double.valueOf(2));
// prints "1.0"!!!

And here's another:

System.out.println(true ? '*' : 0);     // prints "*"
int zero = 0;
System.out.println(true ? '*' : zero);  // prints "42"

And, as you've just discovered:

System.out.println(true  ? 1 : null);   // prints "1"
System.out.println(false ? 1 : null);   // prints "null"

Understanding all the intricacies of the the conditional operator ?: can be quite hard. The best advice to give is to simply not mix types in the second and third operands.

The following quote is an excerpt from the lesson of Java Puzzlers, Puzzle 8: Dos Equis:

In summary, it is generally best to use the same type for the second and third operands in conditional expressions. Otherwise, you and the readers of your program must have a thorough understanding of the complex specification for the behavior of these expressions.

JLS references

  • JLS 15.25 Conditional operator ?:
  • JLS 5.1.8 Unboxing Conversion


See the answer to this question. Basically the compiler will attempt to auto-unbox the null value (and throw a null pointer exception). I assume this is the syntax that you had trouble with:

public int test3(int param) { 
    return (param > 0 ? param : null); 
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜