java - 使用三元运算符将 null 作为 int 返回,但 if 语句不允许

标签 java nullpointerexception conditional-operator autoboxing

让我们看一下以下代码段中的简单 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 代码中,即使函数的返回类型是 inttemp() 方法也不会发出编译器错误,而我们正试图返回值 null(通过语句 return true ? null : 0;)。编译时,这显然会导致运行时异常NullPointerException

但是,如果我们用 if 语句(如在 same() 方法中)表示三元运算符,这似乎也是错误的,确实发出编译时错误!为什么?

最佳答案

编译器将 null 解释为对 Integer 的空引用,为条件运算符应用自动装箱/拆箱规则(如 Java Language Specification, 15.25 中所述),并且快乐地前进。这将在运行时生成 NullPointerException,您可以通过尝试来确认。

关于java - 使用三元运算符将 null 作为 int 返回,但 if 语句不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8098953/

相关文章:

java - 如何使用 Java Optional 优雅地替换三元运算符

java - Spring 中的 quartz 作业尚未启动

java.lang.NullPointerException : Attempt to read from field 'long org.opencv.core.Mat.nativeObj' on a null object reference

java - Spring DI NullPointerException @Autowired 失败

c - (分配中的左值无效)当我运行它时发生此错误。这是什么意思?

java - if 与条件条件相比的速度

java - If 语句中的访问方法结果

java - org.apache.axis2.AxisFault 连接被拒绝

java - 寻找最近的点

Java Map.put() 抛出空指针