为什么这段代码可以编译?我原本以为编译器会抱怨“类型不匹配:无法将null转换为布尔值”,但它没有。实际运行时,它只是因为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)*