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

标签 java

<分区>

这段代码如何编译?我本以为编译器会提示“类型不匹配:无法从 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 认为三元表达式的类型是boolean。编译器将 null 视为 Boolean,即对 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 中拆箱一个 boolean 时触发异常的原因。

关于java - 为什么返回 boolean 值的方法在返回使用三元运算符时仍然可以编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585857/

相关文章:

java - EOFException 的奇怪行为

java - selenium chrome 驱动程序选择证书弹出确认不起作用

java - 如何在 Java 中使用 zxing 从手持条码扫描仪读取条码

java - 加速利用 2 个大数组列表的嵌套 for 循环

java - 关闭 session 后立即触发 destroyListener

java - 如何监听多个 Gmail 帐户上传入的电子邮件 - Java

java - 为什么 Byte.compare() 和 Integer.compare() 的实现方式不同?

java - 计数输出不正确

java - Netbeans 按钮自定义

java - 使用 axios POST 请求将 JSON 数据作为 multipart/form-data 发送