這個問題已經在這裡有了答案: > Booleans, conditional operators and autoboxing 4個
該代碼如何編譯?我本來希望編譯器抱怨“類型不比對:無法從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)*
解決方法:
Java認為三元表達式的類型為布爾值.編譯器将null視為布爾值,即對原始類型的boolean應用裝箱轉換的結果.
這是語言規範的相關部分:
15.25 The type of a conditional expression is determined as follows:
…
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
語言規範指出,裝箱/拆箱轉換在必要時應用于表達式條件所選擇的操作數.這就是當代碼嘗試從null中取消布爾值時觸發異常的原因.
标簽:java
來源: https://codeday.me/bug/20191110/2014599.html