让我们在以下片段中查看简单的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()方法中)表示三元运算符,这似乎是错误的,它确实会发出编译时错误!为什么?
null到Integer...看起来就像是在向我“猜测”或“使事情起作用” ...
Integer foo() { return "1"; }不会编译。)
int foo = (true ? null : 0)与new Integer(null)这两个编译罚款,第二个是自动装箱的明确形式。