加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么返回null(需要布尔值)作为三元运算符编译的结果?

发布时间:2020-12-14 16:44:21 所属栏目:Java 来源:网络整理
导读:参见英文答案 Booleans,conditional operators and autoboxing4个 我刚刚注意到的一种好奇心,而不是一个问题. 我不被允许写 public boolean x() { return null;} 或这个: public boolean x() { if (DEBUG) { return true; } else { return null; }} 但我被
参见英文答案 > Booleans,conditional operators and autoboxing4个
我刚刚注意到的一种好奇心,而不是一个问题.

我不被允许写

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读