Double!= null导致NullPointerException

Ric*_*ard 6 java nullpointerexception

我有以下代码片段让我烦恼,其中currentRate和secondCurrentRate是Double对象,正确定义:

(currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
Run Code Online (Sandbox Code Playgroud)

这应该检查每个Double的null-ness并相应地赋值null.但是,如果secondCurrentRate为null,则会导致NullPointerException.我已将代码段更改为:

(currentRate == null | secondCurrentRate == null) ? null : currentRate * secondCurrentRate;
Run Code Online (Sandbox Code Playgroud)

这可以按预期工作.我的问题是为什么会发生这种情况?如果我在对象上调用某个方法,我可以理解它,但我的理解是当在null对象上调用方法时抛出NullPointerExceptions.有一个null对象,但没有方法调用.

任何人都可以对此提供任何见解吗?这是在Java 5中运行的.

Col*_*ert 5

我认为你的问题在其他地方.

这有效:

    Double currentRate=null, secondCurrentRate =null;
    Double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
Run Code Online (Sandbox Code Playgroud)

但如果你这样做了,它会导致NPE:

    Double currentRate=null, secondCurrentRate =null;
    double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
Run Code Online (Sandbox Code Playgroud)