本文介绍了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:d2 double 。条件表达式必须具有单个返回类型。遵循二进制数字促销规则, d2 自动装箱到 double ,这会导致 NullPointerException d2 == null

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.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,在三元表达式中具有自动装箱功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 13:47