返回 null 作为三元运算符允许的 int 而不是 if 语句 [英] Returning null as an int permitted with ternary operator but not if statement

查看:21
本文介绍了返回 null 作为三元运算符允许的 int 而不是 if 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看以下片段中的简单 Java 代码:

Let's look at the simple Java code in the following snippet:

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.

In this simplest of Java code, the temp() method issues no compiler error even though the return type of the function is int, and we are trying to return the value null (through the statement return true ? null : 0;). When compiled, this obviously causes the run time exception NullPointerException.

然而,如果我们用 if 语句(如在 same() 方法中)表示三元运算符,则似乎同样的事情是错误的, 确实 会发出编译时错误!为什么?

However, it appears that the same thing is wrong if we represent the ternary operator with an if statement (as in the same() method), which does issue a compile-time error! Why?

推荐答案

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

The compiler interprets null as a null reference to an Integer, applies the autoboxing/unboxing rules for the conditional operator (as described in the Java Language Specification, 15.25), and moves happily on. This will generate a NullPointerException at run time, which you can confirm by trying it.

这篇关于返回 null 作为三元运算符允许的 int 而不是 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆