在三元表达式中使用自动装箱的 NullPointerException [英] NullPointerException with autoboxing in ternary expression

查看:16
本文介绍了在三元表达式中使用自动装箱的 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下 Java 代码:

Run the following Java code:

boolean b = false;
Double d1 = 0d;
Double d2 = null;
Double d = b ? d1.doubleValue() : d2;

为什么会出现 NullPointerException?

Why is there a NullPointerException?

推荐答案

条件表达式的返回类型 b ?d1.doubleValue : d2double.条件表达式必须具有单一的返回类型.遵循二进制数字提升的规则,d2 自动拆箱为 double,当 d2 == null 时会导致 NullPointerException代码>.

The return type of the conditional expression b ? d1.doubleValue : d2 is double. A conditional expression must have a single return type. Following the rules for binary numeric promotion, d2 is autounboxed to a double, which causes a NullPointerException when d2 == null.

来自语言规范的第 15.25 节:

From the language spec, section §15.25:

否则,如果第二个和第三个操作数的类型是可转换(第 5.1.8 节)为数字类型,那么有几种情况:...

Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases: ...

否则,应用二进制数字提升(第 5.6.2 节)到操作数类型,以及条件表达式是二、三类提升型操作数.注意二进制数促销执行拆箱转换(§5.1.8) 和值集转换(第 5.1.13 节).

Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).

这篇关于在三元表达式中使用自动装箱的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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