【发布时间】:2011-12-27 06:57:48
【问题描述】:
我们看下面sn-p中的简单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 代码中,temp() 方法不会发出编译器错误,即使函数的返回类型是 int,我们正试图返回值 null(通过语句 return true ? null : 0; )。编译时,这显然会导致运行时异常NullPointerException。
但是,如果我们用if 语句(如在same() 方法中)表示三元运算符,似乎同样的事情是错误的,确实会发出编译时错误!为什么?
【问题讨论】:
-
另外,
int foo = (true ? null : 0)和new Integer(null)都可以正常编译,第二个是自动装箱的显式形式。 -
@Izkata 这里的问题是让我理解为什么编译器试图将
null自动装箱到Integer... 这对我来说就像“猜测”或“让事情正常进行” “... -
...嗯,我想我在那里有答案,因为 Integer 构造函数(我发现的文档用于自动装箱)允许将字符串作为参数(可以是空值)。但是,他们还说构造函数的行为与方法 parseInt() 相同,后者会在传递 null 时抛出 NumberFormatException...
-
@Izkata - Integer 的 String 参数 c'tor 不是自动装箱操作。字符串不能自动装箱为整数。 (函数
Integer foo() { return "1"; }不会编译。) -
酷,学习了有关三元运算符的新知识!
标签: java nullpointerexception conditional-operator autoboxing