微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 为什么返回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.

原文地址:https://www.jb51.cc/java/124517.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐