让我们看一下以下代码段中的简单 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 代码中,即使函数的返回类型是 int
,temp()
方法也不会发出编译器错误,而我们正试图返回值 null
(通过语句 return true ? null : 0;
)。编译时,这显然会导致运行时异常NullPointerException
。
但是,如果我们用 if
语句(如在 same()
方法中)表示三元运算符,这似乎也是错误的,确实发出编译时错误!为什么?
最佳答案
编译器将 null
解释为对 Integer
的空引用,为条件运算符应用自动装箱/拆箱规则(如 Java Language Specification, 15.25 中所述),并且快乐地前进。这将在运行时生成 NullPointerException
,您可以通过尝试来确认。
关于java - 使用三元运算符将 null 作为 int 返回,但 if 语句不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8098953/