相关疑难解决方法(0)

将null返回为允许使用三元运算符的int,而不是if语句

让我们看看以下代码段中的简单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)

java autoboxing nullpointerexception conditional-operator

185
推荐指数
5
解决办法
2万
查看次数

布尔值,条件运算符和自动装箱

为什么这会抛出 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

128
推荐指数
3
解决办法
2万
查看次数