Java 8中的三元运算符,使用Maven编译

Ste*_*yts 5 java compiler-errors nullpointerexception primitive-types maven

考虑这个课程:

package be.duo.test;

public class Main {

    public static void main(String[] args) {
        Main main = new Main();
        main.execute();
    }

    private void execute() {
        for(int i = 0; i < 10; i++) {
            System.out.println("" + method());
        }
    }

    private int method() {
        return (Math.random() > 0.5d) ? 1 : null;
    }

}
Run Code Online (Sandbox Code Playgroud)

method()具有返回类型int,它是一种基本类型.

考虑return语句中使用的三元运算符:

  • 它用Java 8默认编译器编译,但这会在运行时导致NullPointerException,为什么?
  • 使用Maven会导致编译时错误
[ERROR] error: incompatible types: bad type in conditional expression
[ERROR] <null> cannot be converted to int
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释为什么它表现不同吗?

Rad*_*def 3

据我所知,它在 Java 8 下应该是合法的。

\n\n

参见表15.25-E。条件表达式类型(参考第三部分第三个操作数)

\n\n
3rd \xe2\x86\x92 null\n2nd \xe2\x86\x93        \nint   lub(Integer,null)\n
Run Code Online (Sandbox Code Playgroud)\n\n

lub(Integer,null)应该Integer。基本上,如果您有 形式的条件boolean ? int : null,则表达式的结果应该是Integer并且它会被拆箱。(我想你已经知道会发生什么了。)

\n\n

所以根据规范它应该是相同的。

\n\n

看起来像一个编译器错误。已经发现了很多这样的内容,我会说尝试更新到最新版本。

\n