gpt4 book ai didi

java - 为什么返回 boolean 值的方法在返回使用三元运算符时仍然可以编译?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:50 26 4
gpt4 key购买 nike

<分区>

这段代码如何编译?我本以为编译器会提示“类型不匹配:无法从 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)*

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com