java - 为什么作为三元运算符编译的结果返回 null(期望 boolean 值)?

标签 java ternary-operator

<分区>

我刚刚注意到的好奇心,而不是问题。

我不允许写

public boolean x() {
  return null;
}

或者这个:

public boolean x() {
  if (DEBUG) {
    return true;
  } else {
    return null;
  }
}

但我可以写

public boolean x() {
  return DEBUG ? true : null;
}

这是为什么? (如果采用“else”分支,它似乎会抛出 NPE。)

最佳答案

作为jls状态:

The type of a conditional expression is determined as follows: If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression. 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.

这意味着 java 允许 null,因为它可以用来生成 Boolean 的实例,它可以拆箱为 boolean(阅读有关更多信息的 jls 中关于 boxing 的部分)。但是由于 Boolean 实例被初始化为 null,对 booleanValue() 的调用将导致 NullPointerException

关于java - 为什么作为三元运算符编译的结果返回 null(期望 boolean 值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32266052/

相关文章:

javascript - 当三元测试大于/小于条件时,简写是什么?

java - 为什么三元运算符会意外地转换整数?

java - 动态检索 JUnit 类

Java PrintWriter 仅显示 mysql 数据库中的一条记录

java - Maven svn : E215004: Authentication failed and interactive prompting is disabled; see the --force-interactive option

java - 一张一张地播放音频文件?

java - 我可以在字符串连接中使用条件三元运算符吗?

java - 我应该使用哪种工厂设计模式?

java - 当我使用三元运算符时抛出 NullPointerException

PHP:是否有空合并运算符的反面?