返回NULL作为三元运算符允许的int,但不允许if语句

返回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 = new Main();
        System.out.println(m.temp());
        System.out.println(m.same());
    }}

在最简单的Java代码中,temp()方法不会发出编译器错误,即使函数的返回类型为int,我们正在尝试返回值。null(通过声明return true ? null : 0;)。在编译时,这显然会导致运行时异常。NullPointerException.

但是,如果我们用if语句(如same()方法),其中是吗?发出编译时错误!为什么?


GCT1015
浏览 738回答 3
3回答

九州编程

实际上,这一切都是在Java语言规范.条件表达式的类型确定如下:如果第二个和第三个操作数具有相同的类型(这可能是空类型),那么这就是条件表达式的类型。因此,您(true ? null : 0)获取int类型,然后自动装箱到Integer。尝试像这样的东西来验证这一点(true ? null : null)就会得到编译器错误。

阿波罗的战车

编译器解释null作为对Integer,为条件运算符应用自动装箱/取消装箱规则(如Java语言规范,15.25),并愉快地向前移动。这将生成一个NullPointerException在运行时,您可以通过尝试来确认。

Helenr

我认为,Java编译器解释true ? null : 0作为Integer表达式,该表达式可以隐式转换为int,可能会给予NullPointerException.对于第二种情况,表达式null是特别的空型 看见,所以密码return null造成类型错配。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java