为什么将三元语句中的空值分配给布尔变量会引发NPE? [英] Why does assigning a null value from a ternary statement to a Boolean variable throw a NPE?

查看:59
本文介绍了为什么将三元语句中的空值分配给布尔变量会引发NPE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一部分这样的代码:

I have a part of code like this:

public static void main(String[] args) throws Exception {
    String trueValue = Boolean.TRUE.toString();
    String fieldValue = null;
    Boolean defaultValue = null;

    Boolean value = (fieldValue != null ? trueValue.equalsIgnoreCase(fieldValue) : defaultValue);

    System.out.println(value);
}

defaultValue 为不等于 null ,代码可以正常工作,但是当 defaultValue null JVM引发 NullPointerException 。这段代码是使用jdk 1.6.45编译的。

When defaultValue is not equal to null the code works fine, but when defaultValue is null the JVM throws a NullPointerException. This code was compiled using jdk 1.6.45.

为什么会出现此异常?

推荐答案

Java语言规范说:


如果第二个和第三个操作数之一是原始类型 T ,另一个的类型是将装箱转换(第5.1.7节)应用于 T 的结果,则条件表达式的类型为 T

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.

这篇关于为什么将三元语句中的空值分配给布尔变量会引发NPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆