让我们看一下以下代码段中的简单 Java 代码:
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());
}
}
在这个最简单的 Java 代码中,temp()
即使函数的返回类型是int
,并且我们试图返回值null
(通过语句return true ? null : 0;
),该方法也不会发出编译器错误。编译时,这显然会导致运行时异常NullPointerException
。
但是,如果我们用一个if
语句(如在same()
方法中)来表示三元运算符,这似乎也是错误的,这确实会引发编译时错误!为什么?