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

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

问题描述

我有一段这样的代码:

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 时,代码工作正常,但是当 defaultValuenull 时,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.

为什么我会收到此异常?

Why did I get this exception?

推荐答案

Java 语言规范 说:

如果第二个和第三个操作数之一是原始类型T,而另一个的类型是对T应用装箱转换(第5.1.7节)的结果code>,则条件表达式的类型为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天全站免登陆