<分区>
这段代码如何编译?我本以为编译器会提示“类型不匹配:无法从 null 转换为 boolean 值”,但事实并非如此。它只是在运行时因 NullPointerException 而失败。
public static void main(String[] args) throws Exception {
System.out.println("this throws a NPE: " + whyIsThisPossible(1, 2));
}
private static boolean whyIsThisPossible(int a, int b) {
return a + b == 2 ? true : null;
}
Exception in thread "main" java.lang.NullPointerException
at FunkyMethodTest.whyIsThisPossible(FunkyMethodTest.java:10)
at FunkyMethodTest.main(FunkyMethodTest.java:5)*