让我们看看以下代码段中的简单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 = …Run Code Online (Sandbox Code Playgroud) 为什么这会抛出 NullPointerException
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
Run Code Online (Sandbox Code Playgroud)
虽然这不是
public static void main(String[] args) throws Exception {
Boolean b = true ? null : false;
System.out.println(b); // null
}
Run Code Online (Sandbox Code Playgroud)
?
解决办法是更换的方式false通过Boolean.FALSE,以避免null被拆箱到boolean,可呈现是不可能的.但这不是问题.问题是为什么?JLS中是否有任何引用证实了这种行为,尤其是第二种情况?
java autoboxing boolean nullpointerexception conditional-operator