【发布时间】:2018-10-01 19:19:11
【问题描述】:
这个小程序在三元运算符的行抛出NullPointerException:
public class Main {
int someMethod() {
return (true ? null : 0);
}
public static void main(String[] args) {
Main obj= new Main();
obj.someMethod();
}
}
我理解原因是 null 不能转换为 int。
然而,问题是为什么Java编译器允许这种代码通过,而像下面这样的东西会导致编译时错误:
int i = null; //Error: incompatible types: <nulltype> cannot be converted to int
【问题讨论】:
-
您是否尝试过运行第一个版本的代码(尽管它可以编译)
-
好吧,如果这是一个错误,那么它是不允许的。不过反正代码没有错。
-
@user7 是的,尝试过,它在运行时抛出了 npe,如所述。
-
因为它是自动装箱,但实际的拆箱操作要到运行时才会发生。
标签: java compiler-errors nullpointerexception runtime-error ternary-operator