Java中的棘手三元运算符 - 自动装箱 [英] Tricky ternary operator in Java - autoboxing

查看:101
本文介绍了Java中的棘手三元运算符 - 自动装箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看以下代码段中的简单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代码中, temp()方法没有编译错误,即使函数的返回类型是 int ,我们正试图返回值 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.

这篇关于Java中的棘手三元运算符 - 自动装箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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