【发布时间】:2015-03-17 16:42:03
【问题描述】:
当我这样写时在 Java 中
public int method(boolean b) {
if (b)
return null;
else
return 0;
}
编译器抱怨incompatible types,但如果用速记代替它
public int method(boolean b) {
return (b ? null : 0);
}
编译器不会报错,而且会有NPE。
所以我的问题是
- 为什么编译器不抱怨
- 为什么是
NPE?
【问题讨论】:
-
2. NPE 因为 Integer.intValue() 在 null 上调用。原始类型 int 不能为 null,
标签: java if-statement nullpointerexception return