返回null作为三元运算符允许的int值,但if语句则不允许 [英] Returning null as an int permitted with ternary operator but not if statement
问题描述
下面的代码段让我们看一下简单的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代码中,即使函数的返回类型为int
,temp()
方法也不会发出编译器错误,并且我们正在尝试返回值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.
这篇关于返回null作为三元运算符允许的int值,但if语句则不允许的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!