【发布时间】:2011-04-22 09:04:52
【问题描述】:
为什么会抛出NullPointerException
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
虽然没有
public static void main(String[] args) throws Exception {
Boolean b = true ? null : false;
System.out.println(b); // null
}
?
解决方案是顺便将false 替换为Boolean.FALSE 以避免null 被拆箱为boolean——这是不可能的。但这不是问题。问题是为什么? JLS 中是否有任何参考资料证实了这种行为,尤其是第二种情况?
【问题讨论】:
-
哇,自动装箱是......呃......对于java程序员来说,惊喜的源泉,不是吗? :-)
-
我遇到了类似的问题,令我吃惊的是它在 OpenJDK 虚拟机上失败,但在 HotSpot 虚拟机上工作......一次编写,随处运行!
标签: java nullpointerexception boolean conditional-operator autoboxing