Tricky ternary operator in Java
Let's look at the simple Java code in the following snippet:
public class Main {
private int temp() {
return true ? null : 0;
// No compiler error - the compiler allows a return value of null
// in a method signature that returns an int.
}
private int same() {
if (true) {
return null;
// The same is not possible with if,
// and causes a compile-time error - incompatible types.
} else {
return 0;
}
}
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.temp());
System.out.println(m.same());
}
}
In this simplest of Java code, the temp()
method issues no compiler error even though the return type of the function is int
, and we are trying to return the value null
(through the statement return true ? null : 0;
). When compiled, this obviously causes the run time exception NullPointerException
.
However, it appears that the same thing is wrong if we represent the ternary operator with an if
statement (as in the same()
method), which does issue a compile-time error! Why?
The compiler interprets null
as a null reference to an Integer
, applies the autoboxing/unboxing rules for the conditional operator (as described in the Java Language Specification, 15.25), and moves happily on. This will generate a NullPointerException
at run time, which you can confirm by trying it.
I think, the Java compiler interprets true ? null : 0
true ? null : 0
as an Integer
expression, which can be implicitly converted to int
, possibly giving NullPointerException
.
For the second case, the expression null
is of the special null type see, so the code return null
makes type mismatch.
Actually, its all explained in the Java Language Specification.
The type of a conditional expression is determined as follows:
Therefore the "null" in your (true ? null : 0)
gets an int type and then is autoboxed to Integer.
Try something like this to verify this (true ? null : null)
and you will get the compiler error.
上一篇: '?:'的返回类型(三元条件运算符)
下一篇: Java中的Tricky三元运算符