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?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…