让我们来看一下下面代码段中的简单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
,我们试图通过语句 return true?null:0;
返回值为null
。当编译时,显然会导致运行时异常NullPointerException
。然而,如果我们使用一个
if
语句代替三元运算符表示(如same()
方法中),相同的事情看起来就错了,这样做会发出编译时错误!为什么呢?
int foo = (true ? null : 0)
和new Integer(null)
都可以编译通过,后者是自动装箱的显式形式。 - Izkatanull
自动装箱为Integer
... 对我来说这看起来就像是“猜测”或“让事情正常工作”... - Marsellus WallaceInteger foo() { return "1"; }
无法编译通过。) - Ted Hopp